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.
psql
| Command | Meaning |
|---|---|
|
Connect (password from |
|
Run a file or one command |
|
Current connection details |
|
List databases (with sizes) |
|
Switch database |
|
List schemas |
|
List tables |
|
Describe a table: columns, indexes, constraints, storage |
|
Indexes, views, sequences, functions |
|
Roles |
|
Installed extensions |
|
Access privileges; |
|
Show a function’s source |
|
Expanded (vertical) output |
|
Show statement time |
|
psql variables; |
|
Client-side COPY (file on the client machine) |
|
Re-run the last query every 2 seconds |
|
Help for meta-commands and SQL |
|
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 |
|---|---|
|
Whole numbers; identity columns ( |
|
Exact decimals for money; |
|
|
|
|
|
Prefer |
|
|
|
Binary vs text JSON |
|
Arrays, with |
|
Ranges; |
|
Network types |
|
Binary data |
|
pgvector extension |
|
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 |
|---|---|---|
|
Equality, ranges, sorting |
|
|
Equality only |
|
|
Arrays, |
|
|
Geometry, ranges, nearest neighbour, trigrams |
|
|
Partitioned search spaces (tries, quadtrees) |
|
|
Huge, naturally ordered tables (time series) |
|
|
Vector nearest neighbour (pgvector) |
|
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 |
|---|---|
|
Each statement sees data committed before it began |
|
One snapshot per transaction (this level also prevents phantoms in PostgreSQL); may fail with a serialization error |
|
As if transactions ran one at a time; retry on error |
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 |
|
Path as |
|
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 |
|---|---|---|---|
|
128MB |
25% of RAM |
Restart required |
|
4GB |
50-75% of RAM |
Planner hint only |
|
4MB |
4-64MB |
Per sort or hash node, per query |
|
64MB |
256MB-1GB |
Vacuum and index builds |
|
100 |
100-300 behind a pooler |
Restart required |
|
1GB |
4-16GB |
Fewer forced checkpoints |
|
5min |
5-15min |
Longer means slower crash recovery |
|
4 |
1.1 on SSD |
Index scans cost estimate |
|
0.2 |
0.02-0.05 on big tables |
Per table via |
|
2 |
2-4 |
More for analytics |
|
replica |
replica, or logical |
Logical needs a restart |
|
on |
on |
|
|
0 (off) |
e.g. 60s |
Stops forgotten transactions |
|
0 (off) |
per role |
Guard against runaway queries |
|
-1 (off) |
e.g. 500ms |
Log slow statements |