// REF. 13 / DATABASE

Postgres cheat sheet

The Postgres you use past standard SQL: psql meta-commands, jsonb operators, the index types and when each earns its keep, upsert and RETURNING, DISTINCT ON and LATERAL, EXPLAIN, VACUUM, roles and row-level security. Current to PostgreSQL 18, including uuidv7(), virtual generated columns and RETURNING old.x, new.x.

Two habits: store every timestamp as timestamptz, and build production indexes with CONCURRENTLY.

↓ Download the printable PDF free · letter size · no email needed

PSQL

\d table
columns, indexes, constraints
\dt \di \dv \df
list tables, indexes, views, functions
\l \c dbname
list databases; connect to one
\x
expanded output; toggles
\timing
show each query's time
\copy t from 'f.csv'
client-side COPY; the file is local
\e
edit the last query in $EDITOR
\watch 5
re-run the last query every 5 s

Types

timestamptz
always; timestamp forgets the zone
uuid DEFAULT uuidv7()
sortable ids; gen_random_uuid() is v4
jsonb
binary json; indexable, unlike json
text[]
array column; ARRAY['a','b']; 1-indexed
GENERATED ALWAYS AS (e)
virtual by default in 18; add STORED

JSONB

j -> 'k' j ->> 'k'
field as jsonb / as text
j @> '{"k": 1}'
contains; uses a GIN index
j ? 'k'
top-level key exists
j || '{"k": 2}'
shallow merge, right wins
jsonb_set(j, '{k}', '1')
set a value at a path
jsonb_agg(x)
rows into a json array
jsonb_array_elements(j)
a json array into rows

Indexes

INDEX CONCURRENTLY ...
no write lock; not inside a transaction
USING gin (j)
jsonb, arrays, tsvector
ON t (a) WHERE active
partial: smaller and faster
ON t ((lower(email)))
expression index; double parens
ON t (a) INCLUDE (b)
covering: index-only scans
USING brin (ts)
huge append-only tables, tiny index

Queries

ON CONFLICT DO UPDATE
upsert; SET x = EXCLUDED.x
ON CONFLICT DO NOTHING
skip duplicates quietly
RETURNING *
rows back from insert, update, delete
RETURNING old.x, new.x
before and after — (18)
SELECT DISTINCT ON (a)
first row per a; ORDER BY a first
CROSS JOIN LATERAL (..)
subquery that sees the row to its left
FOR UPDATE SKIP LOCKED
job queue: grab an unlocked row

Dates & text

now()
transaction start, not the wall clock
date_trunc('day', ts)
floor to a unit
ts AT TIME ZONE 'UTC'
convert; tz and naive swap types
to_char(ts, 'HH24:MI')
format; YYYY MM DD HH24 MI SS
x ILIKE '%a%'
case-insensitive LIKE
@@ to_tsquery('a & b')
full text match; GIN the tsvector

Ops

EXPLAIN (ANALYZE) q
runs it; buffers shown by default in 18
VACUUM (ANALYZE) t
reclaim dead rows, refresh stats
VACUUM FULL
rewrites the table; exclusive lock
pg_stat_statements
CREATE EXTENSION; sort by total_exec_time

Access

CREATE ROLE app LOGIN
PASSWORD '...'; NOLOGIN is the default
GRANT SELECT ON t TO r
or ALL TABLES IN SCHEMA s
ALTER DEFAULT PRIVILEGES
grants for tables not yet created
ROW LEVEL SECURITY
ALTER TABLE t ENABLE ...; default deny
CREATE POLICY p ON t
USING (read rule) WITH CHECK (write)

Here be dragons

timestamp, no tz
guessing the zone, wrong twice a year
CREATE INDEX on prod
locks writes; you meant CONCURRENTLY
VACUUM FULL at noon
ACCESS EXCLUSIVE; ops will call
json, not jsonb
slower, fewer operators, no GIN
Postgres Field Manual Desk Mat

// KEEP IT UNDER YOUR KEYBOARD

Postgres Field Manual Desk Mat

from $34 · printed to order in the USA

See the desk mat