How to repeatedly execute query in PostgreSQL

In this article, we will see how to repeatedly execute query in PostgreSQL Server. From PostgreSQL 9.3 onwards introduced \watch meta-command, which allows us to automatically re-execute query like watch utility of some Linux environments. Time specified is in seconds only.

We exit query execution by pressing Ctrl+C.

1. Lets run the simple query to check username, state and query in PostgreSQL.

select datname,usename,state,query from pg_stat_activity where state='active';

2. As maintenance activity, if we want to run this query for 10 seconds then enter the query \watch 10 in psql tool.

\watch 10

3. If we want to stop, then press Ctrl+C.