psql productivity

PostgreSQL · Essentials · 10 min

Fluency in psql makes exploring schemas and debugging production databases much quicker than any GUI.

psql is far more than a prompt. The commands worth memorising:

  • Describe: \d table (columns, indexes, constraints), \d+ (plus sizes and storage), \dn schemas, \du roles, \df functions, \di indexes, \dx extensions. Add a pattern: \dt sales.*.
  • Output: \x auto switches to one-column-per-line display when rows are too wide; \pset null '(null)' makes NULLs visible.
  • Timing: \timing on prints how long each statement took.
  • Editing: \e opens the last query in $EDITOR; \ef func edits a function.
  • Scripts: \i file.sql runs a file; from the shell, psql -f file.sql does the same, and -v ON_ERROR_STOP=1 stops at the first error (always use it in automation).
  • Variables: \set id 42 then SELECT * FROM t WHERE id = :id; — or :'name' for a quoted literal.
  • Re-running: \watch 2 repeats the last query every two seconds, handy for monitoring.
  • Exporting: \copy (next lessons) and \o file to redirect output.

Settings you want every time go in ~/.psqlrc. \set ECHO_HIDDEN on shows the catalog queries behind \d commands — a great way to learn the system catalogs.

Example

# ~/.psqlrc
\set QUIET 1
\x auto
\timing on
\pset null '(null)'
\set ON_ERROR_STOP on
\set QUIET 0

# run a migration script safely from the shell
psql "postgresql://app@localhost/shop" -v ON_ERROR_STOP=1 -f migrate.sql

# inside psql
# shop=# \set uid 42
# shop=# SELECT * FROM orders WHERE user_id = :uid;
# shop=# SELECT count(*) FROM pg_stat_activity \watch 5

Remember

  • \d, \d+, \dn, \du, \df, \di describe objects
  • \x auto and \timing on belong in every ~/.psqlrc
  • Run scripts with -v ON_ERROR_STOP=1 so failures stop the script

Watch out for

  • Running psql -f in CI without ON_ERROR_STOP, so a failed statement is ignored and the script 'succeeds'.

Check yourself

  1. You run psql -f migrate.sql and statement 3 of 10 fails. Without ON_ERROR_STOP, what happens?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: www.postgresql.org/docs/current/app-psql.html