brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: \timing on in psql shows how long each PostgreSQL statement took

Postgresql
~/tips/tip-postgresql-psql-timing

appdb=# \timing on

Prints the run time of every statement so you can compare a query before and after a change.

Before and after adding an index, I want a number. psql can print one after every statement.

appdb=# \timing on
Timing is on.
appdb=# SELECT count(*) FROM orders WHERE customer_id = 42;
 count
-------
    17
Time: 1.943 ms

The time is in milliseconds, and longer runs also get a minutes and seconds part. \timing without an argument toggles it, \timing off turns it off.

It measures the whole round trip as psql sees it: sending the query, the server doing the work, and the result coming back over the network. That makes it different from EXPLAIN ANALYZE, which reports the time inside the server only. A query returning 100000 rows can show a long time here while the server part was quick, because most of it went into transferring and printing rows.

Run a query twice and look at the second time. The first run often reads from disk and the second from cache, and the difference can be large. Compare like with like: same data, same cache state, and preferably a few runs each. To have it on in every session, put \timing on in ~/.psqlrc.

Further reading: psql (\timing)

More Postgresql tips FROM pg_settings FROM pg_hba_file_rules LOAD 'auto_explain'; CREATE EXTENSION pgstattuple; pg_dump -O -x -f mydb.sql mydb All Postgresql tips (24) All topics

Link