PostgreSQL Cheat Sheet

This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production.

A quick reference verified against PostgreSQL 18.6 (postgres:latest). The commands were executed on that server, except the replication and promotion commands, which were run in the two-server setup described in the replication page, and the entries marked as configuration. It uses the shop schema of the running example (customers, products, orders, order_items). For explanations follow the links at the end.

Download the PostgreSQL Cheat Sheet (PDF)

psql

Command Meaning

psql -U postgres -d postgres -h host -p 5432

Connect (password from PGPASSWORD or ~/.pgpass)

psql -f file.sql, psql -c "SELECT 1"

Run a file or one command

\conninfo

Current connection details

\l, \l+

List databases (with sizes)

\c dbname

Switch database

\dn

List schemas

\dt, \dt shop.*

List tables

\d+ shop.products

Describe a table: columns, indexes, constraints, storage

\di, \dv, \ds, \df

Indexes, views, sequences, functions

\du

Roles

\dx

Installed extensions

\dp table

Access privileges; \ddp default privileges

\sf func

Show a function’s source

\x on / \x auto

Expanded (vertical) output

\timing on

Show statement time

\set VAR value, :VAR, :'VAR'

psql variables; \gset stores a query result in variables

\copy tbl TO 'f.csv' CSV HEADER

Client-side COPY (file on the client machine)

\watch 2

Re-run the last query every 2 seconds

\?, \h CREATE INDEX

Help for meta-commands and SQL

\q

Quit

psql "postgresql://postgres:secret@172.17.0.6:5432/postgres?application_name=cheat&connect_timeout=5"
psql "host=172.17.0.6 port=5432 dbname=postgres user=postgres password=secret"
pg_isready -h 172.17.0.6 -p 5432        # 172.17.0.6:5432 - accepting connections

The URI form is postgresql://user:password@host:port/database?param=value; useful parameters are sslmode (disable, prefer, require, verify-full), application_name, connect_timeout and target_session_attrs (read-write picks the primary from a host list). The address shown is the container’s, so substitute your host.

DDL and DML idioms

CREATE TABLE t_demo (
  id      bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  name    text NOT NULL,
  created timestamptz DEFAULT now());
INSERT INTO t_demo (name) VALUES ('a'), ('b') RETURNING id, name;
INSERT INTO t_demo (id, name) OVERRIDING SYSTEM VALUE VALUES (10, 'c')
  ON CONFLICT (id) DO UPDATE SET name = EXCLUDED.name RETURNING *;          -- upsert
UPDATE t_demo SET name = upper(name) WHERE id = 1 RETURNING *;
DELETE FROM t_demo WHERE id = 2 RETURNING id;
MERGE INTO t_demo t USING (VALUES (10,'cc'),(11,'d')) v(id,name) ON t.id = v.id
  WHEN MATCHED THEN UPDATE SET name = v.name
  WHEN NOT MATCHED THEN INSERT (id, name) OVERRIDING SYSTEM VALUE VALUES (v.id, v.name)
  RETURNING merge_action(), t.id, t.name;
ALTER TABLE t_demo ADD COLUMN note text, ADD CONSTRAINT t_demo_name_len CHECK (length(name) < 20);
TRUNCATE t_demo RESTART IDENTITY;

RETURNING works on INSERT, UPDATE, DELETE and MERGE, and merge_action() (PostgreSQL 17+) returned UPDATE for id 10 and INSERT for id 11. Other idioms: INSERT ... ON CONFLICT DO NOTHING, UPDATE ... FROM, DELETE ... USING, SELECT ... FOR UPDATE SKIP LOCKED for work queues, generate_series for test data, COPY for bulk load, CREATE TABLE t2 (LIKE t INCLUDING ALL), and CREATE TABLE p (...) PARTITION BY RANGE (col).

Common data types

Type Notes

integer, bigint, smallint

Whole numbers; identity columns (GENERATED ALWAYS AS IDENTITY) replace serial

numeric(p,s)

Exact decimals for money; double precision and real are inexact

text, varchar(n), char(n)

text has no length penalty; prefer it

boolean

true, false, NULL

timestamptz, timestamp, date, time, interval

Prefer timestamptz

uuid

gen_random_uuid() is built in

jsonb, json

Binary vs text JSON

int[], text[]

Arrays, with ANY(), @> and unnest()

int4range, tstzrange

Ranges; && overlap, @> contains

inet, cidr, macaddr

Network types

bytea

Binary data

vector(n)

pgvector extension

geography, geometry

PostGIS extension

The types behind that table were confirmed with pg_typeof: integer, timestamp with time zone, integer[], jsonb, uuid, numeric, text, inet, int4range and interval.

Indexes by type

Method Good for Example

btree (default)

Equality, ranges, sorting

CREATE INDEX ON orders (customer_id, order_date)

hash

Equality only

CREATE INDEX ON t USING hash (col)

gin

Arrays, jsonb, full-text, trigrams

CREATE INDEX ON products USING gin (attrs jsonb_path_ops)

gist

Geometry, ranges, nearest neighbour, trigrams

CREATE INDEX ON places USING gist (geog)

spgist

Partitioned search spaces (tries, quadtrees)

CREATE INDEX ON t USING spgist (col)

brin

Huge, naturally ordered tables (time series)

CREATE INDEX ON events USING brin (created_at)

hnsw, ivfflat

Vector nearest neighbour (pgvector)

CREATE INDEX ON docs USING hnsw (embedding vector_cosine_ops)

Variants executed above: expression index ON t_demo (lower(name)), partial index ON t_demo (id) WHERE note IS NULL, covering index ON t_demo (name) INCLUDE (created), CREATE INDEX CONCURRENTLY (no write lock; cannot run inside a transaction), REINDEX INDEX CONCURRENTLY, DROP INDEX CONCURRENTLY.

EXPLAIN

EXPLAIN SELECT * FROM shop.customers WHERE id = 'c-1';                                  -- estimates only, no execution
EXPLAIN (ANALYZE, BUFFERS) SELECT ...;                                                  -- runs it; real times and buffers
EXPLAIN (ANALYZE, BUFFERS, VERBOSE, SETTINGS, WAL, SERIALIZE) SELECT ...;               -- everything
EXPLAIN (FORMAT JSON) SELECT ...;                                                       -- also TEXT, XML, YAML
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF) SELECT ...;                       -- stable, compact output
 Index Scan using customers_pkey on shop.customers (actual rows=1.00 loops=1)
   Output: id, name, email, city, tier, created_at
   Index Cond: (customers.id = 'c-1'::text)
   Index Searches: 1
   Buffers: shared hit=2
 Settings: search_path = 'shop, public'
 Planning:
   Buffers: shared hit=49
 Serialization: output=1kB  format=text

(Trimmed.) EXPLAIN ANALYZE executes the statement; wrap data-modifying ones in BEGIN; ... ROLLBACK;. Scan nodes to know: Seq Scan, Index Scan, Index Only Scan, Bitmap Heap Scan (with Recheck Cond), Parallel Seq Scan; join nodes: Nested Loop, Hash Join, Merge Join.

Transactions, isolation levels and locks

Isolation level Behaviour

READ COMMITTED (default)

Each statement sees data committed before it began

REPEATABLE READ

One snapshot per transaction (this level also prevents phantoms in PostgreSQL); may fail with a serialization error

SERIALIZABLE

As if transactions ran one at a time; retry on error 40001

BEGIN ISOLATION LEVEL SERIALIZABLE READ ONLY; SHOW transaction_isolation; COMMIT;   -- serializable
SHOW default_transaction_isolation;                                                  -- read committed
SELECT * FROM shop.orders WHERE status='open' ORDER BY id FOR UPDATE SKIP LOCKED LIMIT 1;
SELECT pg_try_advisory_lock(42), pg_advisory_unlock(42);                             -- t, t

Row locks: FOR UPDATE, FOR NO KEY UPDATE, FOR SHARE, FOR KEY SHARE, with NOWAIT or SKIP LOCKED. Table lock modes run from ACCESS SHARE (plain SELECT) to ACCESS EXCLUSIVE (DROP, VACUUM FULL, most ALTER TABLE). Find blockers with pg_blocking_pids(pid) and pg_locks.

JSON operators

Operator Meaning

->, ->>

Field as jsonb / as text

#>, #>>

Path as jsonb / as text

@>, <@

Contains / is contained in

?, ?|, ?&

Key exists / any key / all keys

||

Merge

-, #-

Delete key / delete path

@?, @@

jsonpath exists / predicate

Functions: jsonb_set, jsonb_insert, jsonb_build_object, jsonb_agg, jsonb_each, jsonb_array_elements, jsonb_to_recordset, jsonb_path_query, to_jsonb, jsonb_pretty. SQL/JSON: JSON_VALUE, JSON_QUERY, JSON_EXISTS, JSON_TABLE. Index with USING gin (col jsonb_path_ops) for containment or a B-tree on ((col->>'key')) for one field. Details in JSON & JSONB.

Administration and monitoring

SELECT pid, state, wait_event_type, wait_event, pg_blocking_pids(pid), left(query,60) FROM pg_stat_activity WHERE state <> 'idle';
SELECT pg_cancel_backend(pid);       SELECT pg_terminate_backend(pid);
SELECT pg_size_pretty(pg_database_size(current_database())), pg_size_pretty(pg_total_relation_size('shop.orders'));
SELECT relname, n_live_tup, n_dead_tup, last_autovacuum FROM pg_stat_user_tables ORDER BY n_dead_tup DESC LIMIT 5;
SELECT relname, seq_scan, idx_scan FROM pg_stat_user_tables;
SELECT datname, age(datfrozenxid) FROM pg_database;                 -- wraparound watch
SELECT * FROM pg_stat_statements ORDER BY total_exec_time DESC LIMIT 5;   -- needs the extension
SELECT pg_reload_conf();   SHOW work_mem;   ALTER SYSTEM SET work_mem = '32MB';   SELECT pg_postmaster_start_time();
VACUUM (VERBOSE, ANALYZE) shop.orders;   REINDEX TABLE CONCURRENTLY shop.orders;   ANALYZE;
CREATE ROLE app LOGIN PASSWORD 'secret';   GRANT SELECT ON ALL TABLES IN SCHEMA shop TO app;
ALTER DEFAULT PRIVILEGES IN SCHEMA shop GRANT SELECT ON TABLES TO app;

Authentication is configured in pg_hba.conf (check it with SELECT * FROM pg_hba_file_rules;), reloaded with pg_reload_conf().

Backup and restore commands

pg_dump -U postgres -Fc -n shop -f shop.dump postgres          # custom-format dump
pg_dump -U postgres -Fd -j 4 -f shop_dir postgres              # parallel directory dump
pg_dumpall -U postgres --globals-only > globals.sql            # roles and tablespaces
pg_restore -l shop.dump                                        # list contents
pg_restore -U postgres -d newdb -j 4 --no-owner shop.dump      # parallel restore
pg_basebackup -U postgres -D /backup/base -Fp -X stream -c fast -P
pg_verifybackup /backup/base

Point-in-time recovery settings (in postgresql.auto.conf, with an empty recovery.signal file): restore_command = 'cp /archive/%f %p', recovery_target_time = '2026-11-10 19:08:43+00', recovery_target_action = 'promote'. Archiving needs archive_mode = on and archive_command. See Backup & Restore.

Replication checks

SELECT application_name, state, sync_state, replay_lag FROM pg_stat_replication;        -- on the primary
SELECT status, sender_host, slot_name FROM pg_stat_wal_receiver;                        -- on the standby
SELECT now() - pg_last_xact_replay_timestamp() AS replay_delay;                          -- on the standby
SELECT slot_name, active, wal_status FROM pg_replication_slots;
SELECT pg_is_in_recovery();   SELECT pg_promote();   SELECT pg_wal_replay_pause();
CREATE PUBLICATION shop_pub FOR TABLE shop.customers;
CREATE SUBSCRIPTION shop_sub CONNECTION 'host=... dbname=... user=...' PUBLICATION shop_pub;

Building a standby: pg_basebackup -h primary -U replicator -D datadir -R -X stream -C -S standby1. Promote with pg_ctl promote -D datadir or SELECT pg_promote();. Logical replication needs wal_level = logical. Details in Replication & High Availability.

Key settings

Values below are the defaults on the 18.6 Docker image, followed by a common starting point for a dedicated server.

Setting Default Typical production Notes

shared_buffers

128MB

25% of RAM

Restart required

effective_cache_size

4GB

50-75% of RAM

Planner hint only

work_mem

4MB

4-64MB

Per sort or hash node, per query

maintenance_work_mem

64MB

256MB-1GB

Vacuum and index builds

max_connections

100

100-300 behind a pooler

Restart required

max_wal_size

1GB

4-16GB

Fewer forced checkpoints

checkpoint_timeout

5min

5-15min

Longer means slower crash recovery

random_page_cost

4

1.1 on SSD

Index scans cost estimate

autovacuum_vacuum_scale_factor

0.2

0.02-0.05 on big tables

Per table via ALTER TABLE ... SET

max_parallel_workers_per_gather

2

2-4

More for analytics

wal_level

replica

replica, or logical

Logical needs a restart

synchronous_commit

on

on

local or off trade durability for speed

idle_in_transaction_session_timeout

0 (off)

e.g. 60s

Stops forgotten transactions

statement_timeout, lock_timeout

0 (off)

per role

Guard against runaway queries

log_min_duration_statement

-1 (off)

e.g. 500ms

Log slow statements