A short reference of SQL syntax I use every day. Examples target PostgreSQL, differences from the standard are mentioned where they matter. For the psql client itself see the psql cheatsheet.
SELECT DISTINCT col1, col2 AS aliasFROM table_name tWHERE conditionGROUP BY col1HAVING aggregate_conditionORDER BY col1 DESC, col2 ASC NULLS LASTLIMIT 10 OFFSET 20;
Logical order of evaluation: FROM → WHERE → GROUP BY → HAVING → SELECT → DISTINCT → ORDER BY → LIMIT. That is why a SELECT alias can be used in ORDER BY but not in WHERE.
Syntax
Description
SELECT *
All columns
SELECT DISTINCT ON (col) ...
First row per col (PostgreSQL only, needs a matching ORDER BY)
LIMIT n OFFSET m
Pagination
FETCH FIRST n ROWS ONLY
Standard SQL form of LIMIT
ORDER BY col NULLS FIRST
Control where NULLs go
SELECT ... FOR UPDATE
Lock selected rows until the end of the transaction
SELECT department, name, salary, RANK() OVER (PARTITION BY department ORDER BY salary DESC) AS rank_in_dept, salary - AVG(salary) OVER (PARTITION BY department) AS diff_from_avgFROM employees;
WITH recent_orders AS ( SELECT customer_id, SUM(total) AS total FROM orders WHERE created_at > now() - interval '30 days' GROUP BY customer_id)SELECT c.name, r.totalFROM recent_orders rJOIN customers c ON c.id = r.customer_id;
Recursive CTE, for example walking a tree:
WITH RECURSIVE subordinates AS ( SELECT id, manager_id, name FROM employees WHERE id = 1 UNION ALL SELECT e.id, e.manager_id, e.name FROM employees e JOIN subordinates s ON e.manager_id = s.id)SELECT * FROM subordinates;
CREATE TABLE orders ( id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, customer_id bigint NOT NULL REFERENCES customers (id) ON DELETE CASCADE, status text NOT NULL DEFAULT 'new' CHECK (status IN ('new', 'paid', 'shipped')), total numeric(10, 2) NOT NULL, created_at timestamptz NOT NULL DEFAULT now(), UNIQUE (customer_id, created_at));
Syntax
Description
CREATE TABLE IF NOT EXISTS t (...)
Create only if missing
CREATE TABLE t AS SELECT ...
Create from a query result
CREATE TEMP TABLE t (...)
Table dropped at the end of the session
DROP TABLE IF EXISTS t CASCADE
Drop a table and everything depending on it
ALTER TABLE t RENAME TO t2
Rename a table
ALTER TABLE t ADD COLUMN c int
Add a column
ALTER TABLE t DROP COLUMN c
Drop a column
ALTER TABLE t ALTER COLUMN c TYPE bigint USING c::bigint
Change a column type
ALTER TABLE t ALTER COLUMN c SET NOT NULL
Add a NOT NULL constraint
ALTER TABLE t ALTER COLUMN c SET DEFAULT 0
Set a default
ALTER TABLE t ADD CONSTRAINT name UNIQUE (c)
Add a named constraint
ALTER TABLE t DROP CONSTRAINT name
Drop a constraint
CREATE INDEX idx ON t (c)
Create an index
CREATE UNIQUE INDEX idx ON t (c) WHERE active
Partial unique index
CREATE INDEX CONCURRENTLY idx ON t (c)
Build an index without blocking writes
CREATE VIEW v AS SELECT ...
Create a view
CREATE MATERIALIZED VIEW v AS SELECT ...
View with stored results, update with REFRESH MATERIALIZED VIEW v