Quick Reference · relational database

postgreSQL cheat sheet

SQL is written top-down (SELECT…FROM…WHERE) but the engine runs it in a fixed, different order. Learn that order once and half of SQL's "gotchas" (aliases, HAVING, window functions) stop being mysterious.

psql client schema (DDL) data (DML) query / read admin & perf destructive most common

Distilled & cross-checked across: postgresql.org · linuxize.com · quickref.me · tigerdata.com · geeksforgeeks.org · codecademy.com · gist.github.com/yokawasa · gist.github.com/Kartones · DataCamp · LearnSQL.com / Vertabelo

Logical query processing order

You write a query SELECT…FROM…WHERE…ORDER BY — but the planner executes it in this sequence. This is why a WHERE clause can't see a SELECT alias, and why ORDER BY can.

1 FROM / JOIN build the row set 2 WHERE filter rows (no aliases) 3 GROUP BY collapse into groups 4 HAVING filter the groups 5 SELECT DISTINCT compute & dedupe columns 6 ORDER BY sort — aliases work here 7 LIMIT / OFFSET trim the final rows EXECUTION RUNS LEFT → RIGHT you typed: SELECT…FROM…WHERE…GROUP BY…HAVING…ORDER BY…LIMIT (written order is almost the reverse of run order)
01Connect & psql Flagsthe command line
02psql Meta-Commandsthe backslash family
03Databases & Schemastop-level containers
04Create & Alter Tablesstructure
05Constraintsdata integrity rules
06Core Data Typeswhat to store columns as
07Query BasicsSELECT, sort, page
08FilteringWHERE clauses
09Joinscombine tables — see diagrams ↓
10Aggregation & Groupingsummarize rows
11Modifying Datawrite operations
12Transactionsall-or-nothing changes
13Indexes & Performancemake reads fast
14Roles & Privilegeswho can do what
15Text, Date & Castingcommon functions
16Backup, Restore & CSVmove data in & out
17Monitoring & Maintenancekeep it healthy
Reading the Placeholdersnotation used throughout

The four core joins

Same two tables, A and B — the shaded region is what each join keeps. Based on the standard SQL join-Venn convention.

INNER JOIN

Only rows where the join condition matches on both sides.

A B A ∩ B

LEFT JOIN

Every row from A, with matches from B where they exist (else NULL).

A B all of A

RIGHT JOIN

Every row from B, with matches from A where they exist (else NULL).

A B all of B

FULL OUTER JOIN

Every row from both sides; unmatched columns come back NULL.

A B A ∪ B

Worth memorizing

WHERE ≠ HAVINGWHERE filters rows before grouping; HAVING filters the groups
DELETE ≠ TRUNCATEDELETE is row-by-row, logged, supports WHERE; TRUNCATE is instant, no WHERE
= NULL is always falseNULL has no equality — use IS [NOT] NULL
SERIAL ≠ IDENTITYSERIAL is legacy sugar; GENERATED ALWAYS AS IDENTITY is the SQL standard
VACUUM ≠ ANALYZEVACUUM reclaims dead-row space; ANALYZE refreshes planner statistics
no USE statementPostgres has no USE db — switch with \c inside psql
UNIQUE index ≠ PRIMARY KEYboth enforce uniqueness, but UNIQUE permits one NULL
autocommit is oneach statement commits immediately unless wrapped in BEGIN…COMMIT