Skip to content

Menu

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=require

Connect with a URI instead of separate host, port and database flags

From the docs, not run by us
psql "service=myservice sslmode=require"

Connect with a key=value conninfo string, here using a named service entry

From the docs, not run by us
psql -c 'SELECT now()' -c 'SELECT version()'

Run one or more commands and exit; -c can be repeated and mixed with -f

From the docs, not run by us
psql -X -f migrate.sql

Run a script file without reading psqlrc, so personal settings can't change the result

From the docs, not run by us
psql -1 -v ON_ERROR_STOP=1 -f migrate.sql

Wrap the whole file in BEGIN/COMMIT and stop at the first error

-1 only works together with -c or -f.

From the docs, not run by us
psql -At -c 'SELECT id FROM users'

Unaligned output with no headers or row-count footer, handy for piping into shell tools

From the docs, not run by us
\c otherdb

Switch the session to another database, reusing the current user and host

From the docs, not run by us
\conninfo

Print which database, user, host and port you are connected to, plus SSL details

From the docs, not run by us

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.

\l

List databases with owner, encoding and access privileges

From the docs, not run by us
\dn

List the schemas in the current database with their owners

From the docs, not run by us
\dt

List tables visible on the current search path

From the docs, not run by us
\dt sales.*

List every table in the sales schema

From the docs, not run by us
\d orders

Show columns, types, defaults, indexes, constraints and triggers of one table

From the docs, not run by us
\d+ orders

Same as \d plus column comments, storage and access method; shows the SQL for a view

From the docs, not run by us
\d

With no pattern, list tables, views, materialized views, sequences and foreign tables together

From the docs, not run by us
\di

List indexes; use \dv for views and \dm for materialized views

From the docs, not run by us
\df

List functions; add a pattern to find one by name

From the docs, not run by us
\du

List roles and their attributes

From the docs, not run by us
\sf my_function

Print the CREATE statement of a function

From the docs, not run by us

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 auto

Switch to one-column-per-line output only when a row is too wide for the screen

From the docs, not run by us
SELECT * FROM users WHERE id = 42 \gx

Run this one query with expanded output without changing the session setting

From the docs, not run by us
\timing on

Print how long each statement took, in milliseconds

From the docs, not run by us
\pset null '(null)'

Print NULL as visible text so you can tell it apart from an empty string

From the docs, not run by us
\o result.txt

Send query output to a file until you run \o with no argument

From the docs, not run by us
SELECT count(*) FROM jobs WHERE state = 'queued' \watch 5

Re-run a query every 5 seconds until you press Ctrl+C; the default interval is 2

From the docs, not run by us

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

Try it: csv-to-sqlFrom the docs, not run by us
\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

From the docs, not run by us
\copy users (id, email) FROM 'users.csv' WITH (FORMAT csv, HEADER)

Load a local CSV into chosen columns of an existing table

Try it: csv-to-sqlFrom the docs, not run by us
\i seed.sql

Run the statements in a file as if you had typed them

From the docs, not run by us
\ir lib/functions.sql

Like \i but resolves the path relative to the script that is running

From the docs, not run by us
\e

Open the current query buffer, or the last query, in $EDITOR and run it when you save

From the docs, not run by us
\errverbose

Repeat the last error with every detail field, including the source location

From the docs, not run by us

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 42

Define a psql variable; \set with no arguments lists them all

From the docs, not run by us
SELECT * FROM users WHERE id = :uid;

Paste a variable's value into SQL as-is

From the docs, not run by us
SELECT * FROM users WHERE email = :'email';

Interpolate a variable as a properly quoted SQL literal

From the docs, not run by us
SELECT * FROM :"tbl";

Interpolate a variable as a quoted identifier, such as a table name

From the docs, not run by us
SELECT max(id) AS last_id FROM orders \gset

Store each column of a one-row result in a variable named after the column

From the docs, not run by us
\set ON_ERROR_STOP on

Stop a script at the first failed statement; psql then exits with status 3

From the docs, not run by us
\set HISTFILE ~/.psql_history-:DBNAME

Keep a separate command history per database (a .psqlrc line from the manual)

From the docs, not run by us

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 \copy so psql reads the file from your machine and streams it over the connection.

  • Splitting a long \copy across several lines or expecting :variables to expand in it.

    Keep \copy on one line, or write COPY ... TO STDOUT and end it with \g filename, which supports both.

  • Running migration scripts with plain psql -f and trusting the exit code.

    By default psql carries on to the next statement after an error. Add -v ON_ERROR_STOP=1 and usually -1 so a failure stops and rolls back.

  • Parsing psql output in a script while your .psqlrc turns on \x or \timing.

    Pass -X to skip startup files, and -At for clean unaligned rows.

  • Reading an empty cell as an empty string when it is actually NULL.

    Set \pset null '(null)' in .psqlrc so the two never look the same.

  • Concatenating user input into SQL with plain :var interpolation.

    Use :'var' for literals and :"var" for identifiers so psql quotes and escapes the value.