psql Cheat Sheet: Meta-Commands, \copy, Variables and .psqlrc
Checked against psql PostgreSQL 19 documentation (19.0 released 2026-11-19) on 28 November 2026. Each section links to the official docs it was checked against.
This sheet is for developers who live in the PostgreSQL terminal client and want the backslash commands without scrolling the manual. Everything here comes from the psql reference page for PostgreSQL 19, the release that shipped on 19 November 2026. psql was not installed on the machine used to write it, so every row is marked as checked in the docs only.
When to use what
Start every unfamiliar database with \l, \dn and \dt, then \d tablename on whatever looks interesting. The plain \d output covers columns, indexes and constraints; add + only when you need comments, storage details or a view's definition, because the wide output wraps badly in a narrow terminal.
For moving data between a file on your laptop and a server, reach for \copy, not the SQL COPY command. COPY ... FROM 'file' reads the file on the database server, needs superuser-level rights and fails with a confusing path error on any managed host. \copy reads and writes on your side of the connection. The trade-off is speed on very large loads, where the manual itself suggests server-side COPY if you have the access.
In scripts, set ON_ERROR_STOP and pass -X so a colleague's .psqlrc can't change the output you parse. Run with -1 when the file must apply completely or not at all. For anything you type more than twice, put it in .psqlrc as a variable and call it with :name. If you are still learning the queries themselves, the SQL formatter tidies a long statement before you paste it, and the Postgres performance tuning post is the next read once \timing shows something slow.
Environment variables PGHOST, PGPORT, PGUSER and PGDATABASE fill in whatever you leave out of the command line.
psql postgresql://dbmaster:5433/mydb?sslmode=requireConnect with a URI instead of separate host, port and database flags
psql "service=myservice sslmode=require"Connect with a key=value conninfo string, here using a named service entry
psql -c 'SELECT now()' -c 'SELECT version()'Run one or more commands and exit; -c can be repeated and mixed with -f
psql -X -f migrate.sqlRun a script file without reading psqlrc, so personal settings can't change the result
psql -1 -v ON_ERROR_STOP=1 -f migrate.sqlWrap the whole file in BEGIN/COMMIT and stop at the first error
-1 only works together with -c or -f.
psql -At -c 'SELECT id FROM users'Unaligned output with no headers or row-count footer, handy for piping into shell tools
\c otherdbSwitch the session to another database, reusing the current user and host
\conninfoPrint which database, user, host and port you are connected to, plus SSL details
Patterns accept * and ? wildcards, and schema.table to limit by schema. System objects are hidden unless you add S or give a pattern that names them.
\lList databases with owner, encoding and access privileges
\dnList the schemas in the current database with their owners
\dtList tables visible on the current search path
\dt sales.*List every table in the sales schema
\d ordersShow columns, types, defaults, indexes, constraints and triggers of one table
\d+ ordersSame as \d plus column comments, storage and access method; shows the SQL for a view
\dWith no pattern, list tables, views, materialized views, sequences and foreign tables together
\diList indexes; use \dv for views and \dm for materialized views
\dfList functions; add a pattern to find one by name
\duList roles and their attributes
\sf my_functionPrint the CREATE statement of a function
Most \d commands accept an x suffix for one-off expanded output, but not straight after \d with a pattern, because \dx already means extensions.
\x autoSwitch to one-column-per-line output only when a row is too wide for the screen
SELECT * FROM users WHERE id = 42 \gxRun this one query with expanded output without changing the session setting
\timing onPrint how long each statement took, in milliseconds
\pset null '(null)'Print NULL as visible text so you can tell it apart from an empty string
\o result.txtSend query output to a file until you run \o with no argument
SELECT count(*) FROM jobs WHERE state = 'queued' \watch 5Re-run a query every 5 seconds until you press Ctrl+C; the default interval is 2
The rest of the line after \copy is taken as its arguments, so the whole command must fit on one line and variables are not expanded inside it.
\copy users TO 'users.csv' WITH (FORMAT csv, HEADER)Export a table to a CSV file on your machine, not the server
\copy (SELECT id, email FROM users WHERE active) TO 'active.csv' WITH (FORMAT csv, HEADER)Export the result of a query instead of a whole table
\copy users (id, email) FROM 'users.csv' WITH (FORMAT csv, HEADER)Load a local CSV into chosen columns of an existing table
\i seed.sqlRun the statements in a file as if you had typed them
\ir lib/functions.sqlLike \i but resolves the path relative to the script that is running
\eOpen the current query buffer, or the last query, in $EDITOR and run it when you save
\errverboseRepeat the last error with every detail field, including the source location
psql reads the system-wide psqlrc and then ~/.psqlrc after connecting. PSQLRC overrides the path, and a file named like ~/.psqlrc-19 is used in preference for that major version.
\set uid 42Define a psql variable; \set with no arguments lists them all
SELECT * FROM users WHERE id = :uid;Paste a variable's value into SQL as-is
SELECT * FROM users WHERE email = :'email';Interpolate a variable as a properly quoted SQL literal
SELECT * FROM :"tbl";Interpolate a variable as a quoted identifier, such as a table name
SELECT max(id) AS last_id FROM orders \gsetStore each column of a one-row result in a variable named after the column
\set ON_ERROR_STOP onStop a script at the first failed statement; psql then exits with status 3
\set HISTFILE ~/.psql_history-:DBNAMEKeep a separate command history per database (a .psqlrc line from the manual)
Worked example: Export the slow rows, fix them locally, load them back
Say a report query feels slow and you also need a CSV of the rows it touches. In one session:
\timing on
\set since '2026-11-01'
\copy (SELECT id, email, plan FROM accounts WHERE created_at >= :'since') TO 'accounts.csv' WITH (FORMAT csv, HEADER)
That last line will not work. \copy takes the rest of the line literally and does no variable interpolation, so :'since' reaches the server as text and you get a syntax error. Write the date into the \copy line, or use the tip from the manual: run the query as COPY (...) TO STDOUT WITH (FORMAT csv, HEADER) and finish it with \g accounts.csv, which does expand variables and may span several lines.
COPY (SELECT id, email, plan FROM accounts WHERE created_at >= :'since')
TO STDOUT WITH (FORMAT csv, HEADER) \g accounts.csv
With \timing on psql prints how long the statement took, in milliseconds. To load an edited file back, create a staging table and use \copy staging FROM 'accounts.csv' WITH (FORMAT csv, HEADER), then update the real table from it in one transaction. I haven't run this here, so check the row count psql reports against wc -l minus the header line.
Common mistakes
Using
COPY table FROM '/Users/me/data.csv'against a remote or managed database.That path is read on the server. Use
\copyso psql reads the file from your machine and streams it over the connection.Splitting a long
\copyacross several lines or expecting:variablesto expand in it.Keep
\copyon one line, or writeCOPY ... TO STDOUTand end it with\g filename, which supports both.Running migration scripts with plain
psql -fand trusting the exit code.By default psql carries on to the next statement after an error. Add
-v ON_ERROR_STOP=1and usually-1so a failure stops and rolls back.Parsing psql output in a script while your
.psqlrcturns on\xor\timing.Pass
-Xto skip startup files, and-Atfor clean unaligned rows.Reading an empty cell as an empty string when it is actually NULL.
Set
\pset null '(null)'in.psqlrcso the two never look the same.Concatenating user input into SQL with plain
:varinterpolation.Use
:'var'for literals and:"var"for identifiers so psql quotes and escapes the value.
Related cheat sheets
Sources
- https://www.postgresql.org/docs/current/app-psql.html
- https://www.postgresql.org/docs/current/release-19.html
How we research: where our facts come from, how often we re-check them, and why no one can pay for a review or a verdict.