Mateusz Mańczak

psql cheatsheet

#postgresql#databases#cheatsheet#ai-generated

A short reference of psql commands I keep forgetting. Meta-commands start with a backslash and are handled by psql itself, not by the server.

Date 18 November 2026 is the first publication date but I allow myself to update this cheatsheet in the future.

I was mostly thinking about writing it for myself to quick access whatever device I run psql on but if you find it useful nothing blocks you from bookmarking this page.

Connecting#

Command Description
psql -h host -p 5432 -U user -d dbname Connect with explicit parameters
psql "postgresql://user:pass@host:5432/dbname" Connect using a connection URI
psql -c "SELECT now();" Run a single command and exit
psql -f script.sql Run commands from a file
psql -l List databases and exit
psql -X Skip ~/.psqlrc
\c dbname Connect to another database
\c dbname user Connect to another database as another user
\conninfo Show current connection info
\q Quit

Listing objects#

Command Description
\l List databases
\dn List schemas
\dt List tables
\dt schema.* List tables in a schema
\dt *.* List tables in all schemas
\dv List views
\dm List materialized views
\ds List sequences
\di List indexes
\df List functions
\dT List data types
\dx List installed extensions
\du List roles
\dp List table privileges
\db List tablespaces

Add + to most of these (for example \dt+) to also show size and description.

Describing objects#

Command Description
\d table Columns, indexes, constraints and triggers of a table
\d+ table Same as above with storage and description
\d index_name Describe an index
\df+ function_name Show function definition and details
\sf function_name Show function source
\sv view_name Show view definition

Output and formatting#

Command Description
\x Toggle expanded (vertical) output
\x auto Use expanded output only when a row is too wide
\timing Toggle query execution time
\pset null '∅' Show NULLs as a custom string
\pset format csv Switch output format (aligned, csv, html, json…)
\a Toggle aligned / unaligned output
\t Toggle showing only rows (no header and footer)
\o file.txt Send query output to a file (\o alone resets)
\pset pager off Turn the pager off, print everything straight to the terminal
\pset pager on Turn the pager on, use it when output doesn’t fit the screen
\pset pager always Always use the pager, even for short output
\pset pager Toggle the pager on / off
psql -P pager=off Start psql with the pager disabled
\setenv PAGER 'less -S' Change the pager program, here less without line wrapping

Query buffer and history#

Command Description
\e Edit the current query in $EDITOR
\ef function_name Edit a function in $EDITOR
\p Print the current query buffer
\r Reset (clear) the query buffer
\g Execute the query buffer (same as ;)
\gx Execute the query and show the result expanded
\watch 2 Re-run the last query every 2 seconds
\s Show command history

Import and export#

Command Description
\copy table TO 'file.csv' CSV HEADER Export a table to CSV on the client
\copy table FROM 'file.csv' CSV HEADER Import a CSV from the client into a table
\copy (SELECT ...) TO 'out.csv' CSV HEADER Export results of a query
\i file.sql Execute commands from a file
\ir file.sql Same as \i, path relative to the current script

\copy reads and writes files on the client machine. The SQL COPY command works on the server and needs the matching privileges.

Variables and scripting#

Command Description
\set name value Set a variable
\set List all variables
\unset name Unset a variable
:name Use a variable’s value in a query
:'name' Use a variable as a quoted literal
\echo text Print text
\set ON_ERROR_STOP on Stop a script on the first error
\set AUTOCOMMIT off Disable autocommit
\! command Run a shell command

Help#

Command Description
\? Help for psql meta-commands
\h List SQL commands with help available
\h CREATE INDEX Syntax help for a specific SQL command

Configuration files#

File Env variable to override Purpose
~/.pgpass PGPASSFILE Stored passwords
~/.pg_service.conf PGSERVICEFILE Named connection profiles
$(pg_config --sysconfdir)/pg_service.conf PGSYSCONFDIR System-wide service file
~/.psqlrc PSQLRC Commands run on every psql start
~/.psql_history PSQL_HISTORY Command history

.pgpass#

One entry per line, five colon-separated fields:

hostname:port:database:username:password
localhost:5432:mydb:myuser:s3cret
*:5432:*:readonly:another-secret
db.example.com:*:prod:admin:p\:ss\\word

.pg_service.conf#

INI format. Each [section] is a service name, with connection parameters as key=value (no spaces needed around =):

# ~/.pg_service.conf
[local]
host=localhost
port=5432
dbname=mydb
user=myuser

[prod]
host=db.example.com
port=5432
dbname=prod
user=admin
sslmode=require

Use a service with:

psql "service=prod"
# or
PGSERVICE=prod psql

.psqlrc#

A file of psql commands and SQL, executed at every startup (skip with psql -X). Version-specific files ~/.psqlrc-16 are also supported.

\set QUIET 1
\pset null '∅'
\pset linestyle unicode
\pset border 2
\pset pager off
\x auto
\timing on
\set HISTSIZE 5000
\set HISTCONTROL ignoredups
\set COMP_KEYWORD_CASE upper
\set PROMPT1 '%n@%/%R%x%# '
\set ON_ERROR_ROLLBACK interactive
\unset QUIET

Prompt escapes used above:

Escape Meaning
%n Session user name
%/ Current database
%M Server host name
%> Server port
%R = normally, ^ in single-line mode, ! if disconnected
%x Transaction status (* in a transaction, ! in a failed one)
%# # for superuser, > otherwise

Connection environment variables#

Variable Equivalent
PGHOST -h
PGPORT -p
PGUSER -U
PGDATABASE -d
PGPASSWORD Password (discouraged, visible in the process environment, prefer .pgpass)
PGSERVICE Service name from .pg_service.conf
PGSSLMODE sslmode (disable, require, verify-full…)
PGCONNECT_TIMEOUT Connection timeout in seconds
PAGER Pager program used by psql
PSQL_EDITOR / EDITOR Editor used by \e

Handy queries#

-- database size
SELECT pg_size_pretty(pg_database_size(current_database()));

-- table size including indexes
SELECT pg_size_pretty(pg_total_relation_size('my_table'));

-- running queries
SELECT pid, state, now() - query_start AS runtime, query
FROM pg_stat_activity
WHERE state <> 'idle'
ORDER BY runtime DESC;

-- cancel / kill a backend
SELECT pg_cancel_backend(1234);
SELECT pg_terminate_backend(1234);