Languages
PostgreSQL Cheat Sheet — psql Commands and SQL Features
The PostgreSQL-specific commands and features beyond standard SQL: psql shortcuts, JSONB, upserts, window functions, and handy admin queries.
Put it into practice with the matching tool.
Run PostgreSQL in the browser →Advertisement
psql meta-commands
psql -h host -U user -d dbConnect to a database\lList databases\c dbnameConnect to another database\dtList tables\d tableDescribe a table — columns, indexes, constraints\duList roles\xToggle expanded output for wide rows\timingShow how long each query takes\i file.sqlRun commands from a file\qQuitTypes and tables
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEYAuto-increment primary key (modern form of SERIAL)uuid DEFAULT gen_random_uuid()Random UUID defaulttimestamptz DEFAULT now()Timestamp with time zonetext / varchar(n)Strings — text is preferred unless you need a limitjsonbBinary JSON — indexable and queryabletext[]Array columnnumeric(10,2)Exact decimal, for moneyWriting data
INSERT ... RETURNING idReturn values from inserted rowsON CONFLICT (email) DO NOTHINGSkip rows that violate a unique constraintON CONFLICT (email) DO UPDATE SET name = EXCLUDED.nameUpsertUPDATE t SET ... FROM other WHERE ...Update using a joinCOPY t FROM '/path/file.csv' CSV HEADERBulk-load a CSV (use \copy in psql for a local file)JSONB
data->'user'Get a JSON field as JSONdata->>'name'Get a JSON field as textdata#>>'{a,b}'Get a nested path as textdata @> '{"active": true}'Contains — can use a GIN indexdata ? 'key'Key existsjsonb_set(data, '{name}', '"Ana"')Return a copy with a value replacedQueries
WITH recent AS (SELECT ...) SELECT ...Common table expressionrow_number() OVER (PARTITION BY a ORDER BY b)Window function — number rows per groupSELECT DISTINCT ON (user_id) ...First row per group (with ORDER BY)ILIKE '%term%'Case-insensitive pattern matchstring_agg(name, ', ')Join values from many rows into one stringgenerate_series(1, 10)Produce a series of numbers or datesIndexes and admin
CREATE INDEX CONCURRENTLY ON t (col)Build an index without locking writesCREATE INDEX ON t USING gin (data)GIN index for JSONB or arraysEXPLAIN ANALYZE SELECT ...Run a query and show the real plan and timingsSELECT * FROM pg_stat_activitySee running queries and connectionsSELECT pg_size_pretty(pg_database_size(current_database()))Database sizeVACUUM ANALYZE tReclaim space and refresh planner statistics