Skip to content
shellhacks.dev
Databases

Time a Query in psql with the \timing Meta-Command

Time a query in psql by turning on the timing meta-command, which prints Time in milliseconds after every statement. Run it again to toggle it off.

1 min read
Summarize in AI

You want to know how long a statement takes from the client's point of view.

Shell
docker run -d --name pgtime -e POSTGRES_PASSWORD=pw postgres:17-alpine > /dev/null
until [ "$(docker logs pgtime 2>&1 | grep -c 'ready to accept connections')" -ge 2 ]; do sleep 1; done
docker exec -i pgtime psql -U postgres -tA <<'SQL'
select pg_sleep(0.3);
\timing on
select pg_sleep(0.3);
select count(*) from generate_series(1, 1000000);
\timing
select pg_sleep(0.3);
SQL
docker rm -f pgtime > /dev/null
Text

Timing is on.

Time: 300.662 ms
1000000
Time: 83.391 ms
Timing is off.

After timing is turned on, psql prints the elapsed time of each statement. The sleep of 0.3 seconds reported Time: 300.662 ms and counting a million generated rows took 83.391 ms. The timing command with no argument toggles the setting, which is why the run then prints Timing is off. and the last statement has no time. The first statement, before timing was on, printed none. See psql.

The figure includes network time and the time to print the result, so it is longer than the server's own measurement; EXPLAIN ANALYZE reports the execution time inside the server. Because the command only toggles when given no argument, write on or off in scripts. This run used PostgreSQL 17.

Share

More snippets

Get new posts by email

One email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.