56 psql Meta-commands
psql’s meta-commands (also called backslash commands) are client-side shortcuts that make interactive exploration of a database fast and pleasant. They are interpreted by the client, not the server — and work both interactively and in files read with psql -f. Once they become muscle memory, you stop reaching for GUI tools for most day-to-day work.
What you’ll learn
- The essential exploration commands (
\l,\dt,\d,\df,\dn) - Help shortcuts (
\?,\h) - Output and formatting commands (
\x,\timing,\pset) - Running scripts and saving output (
\i,\o,\copy) - Customizing your session with
~/.psqlrc
Example
psql -f script.sql processes both SQL and backslash commands. The SQL file linked below shows catalog-query alternatives, useful when the caller is a database driver rather than psql. Do not paste the descriptive labels in this command reference into a script.
The single most useful command is \d table (and its verbose cousin \d+ table). It shows columns, types, defaults, indexes, constraints, foreign keys, and triggers — everything you need to understand a table’s shape.
The single most useful toggle is \x (expanded display). On a row with 30 columns, the default tabular output is unreadable; expanded display prints column | value one per line. Use \x auto to switch only when the row is too wide for the terminal.
\copy is the client-side equivalent of COPY. It reads/writes files on the client machine; COPY reads/writes files on the server. For loading a CSV into a remote PostgreSQL, \copy is what you want.
Run the example
To run the SQL part of this lesson:
Common pitfalls
- Sending
\dtdirectly through a database driver fails because it is psql syntax. It works interactively and in a file executed bypsql -f. \d(no arguments) lists everything in the currentsearch_path— long output. Filter:\dt,\di,\dv, etc.\copyandCOPY:\copyruns on the client (so relative paths are client paths and CSV files come from your machine);COPYruns on the server. Pick the right one based on where the file lives.- Your
psqlrcruns at every session start. A broken statement there can make psql unusable until you fix the file.
~/.psqlrc is where to keep your customizations. Common entries:
From an interactive psql postgres session, run \dt, \d fruits, \df *agg*, then \h SELECT. Toggle \x and run SELECT * FROM pg_indexes LIMIT 1; to see expanded output. Run a query and pipe to a file: \o out.txt, SELECT * FROM fruits;, \o (to stop redirecting).
Downloads
SQL file: psql-meta-commands.sql · All lesson files · Setup guide