← Back to PostgreSQL, page 2

postgresql-0029 · Easy fresher

Which psql meta-commands should every PostgreSQL developer know?

psql commands start with a backslash and are handled by the client, not the server. The everyday ones are \l (databases), \c (connect), \dt and \d name (tables and their structure), \dn (schemas), \df (functions), \x (expanded output), \timing, \e (edit the last query) and \i (run a file). \? lists them all.

Full answer

psql is the standard command-line client, and its meta-commands are processed by psql itself, so they do not work from application drivers. (The commands below were not run here; this bank's examples run through a driver.)

text
\l                 list databases
\c shop            connect to database shop
\dn                list schemas
\dt sales.*        list tables in schema sales
\d+ orders         columns, indexes, constraints and comments of orders
\di                list indexes
\df *refund*       list functions matching a pattern
\x auto            switch to expanded output for wide rows
\timing on         show how long each statement takes
\e                 edit the last query in $EDITOR
\i migrate.sql     run a file
\copy t FROM 'x.csv' CSV HEADER   client-side CSV import
\set ON_ERROR_STOP on             stop scripts at the first error

Two habits help in production work: run psql -X in scripts so personal settings in .psqlrc do not change behaviour, and set ON_ERROR_STOP so a failed statement does not let the rest of a migration continue. \copy reads files on the client machine, unlike the server-side COPY command, which reads files on the database server.

Key points

  • Meta-commands are handled by psql
  • \d family describes objects
  • \x and \timing aid reading and tuning
  • \copy reads client-side files
  • ON_ERROR_STOP for scripts

Common mistakes

  • Sending meta-commands through an application driver
  • Running scripts without ON_ERROR_STOP

Follow-ups

  • How does \copy differ from COPY?
  • What is .psqlrc used for?

Tips

  • Mention ON_ERROR_STOP