Repeatedly executing a query in psql
Sometimes, we want to execute a query more than once, repeated at regular intervals; in this recipe, we will look at an interesting psql
command that does exactly that.
How to do it…
The \watch
meta-command allows psql
users to automatically (and continuously) re-execute a query. This behavior is similar to the watch
utility of some Linux and Unix environments.
In the following example, we will run a simple query on pg_stat_activity
and ask psql
to repeat it every 5 seconds. You can exit at any time by pressing Ctrl + C:
postgres=# SELECT count(*) FROM pg_stat_activity;
count
-------
6
(1 row)
postgres=# \watch 5
Fri 27 Oct 2023 00:49:06 BST (every 5s)
count
-------
6
(1 row)
<snip>
There’s more…
For further information about the psql utility, please refer to the PostgreSQL documentation at https://www.postgresql.org/docs/current/static/app-psql.html.