Mateusz Mańczak

SQL syntax cheatsheet

#sql#postgresql#databases#cheatsheet#ai-generated

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.

Querying#

SELECT DISTINCT col1, col2 AS alias
FROM table_name t
WHERE condition
GROUP BY col1
HAVING aggregate_condition
ORDER BY col1 DESC, col2 ASC NULLS LAST
LIMIT 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 ... FOR UPDATE SKIP LOCKED Skip rows locked by others (job queues)

Filtering#

Syntax Description
=, <> (or !=), <, <=, >, >= Comparison
a AND b, a OR b, NOT a Boolean logic
col BETWEEN 1 AND 10 Inclusive range
col IN (1, 2, 3) Matches any value in the list
col IN (SELECT ...) Matches any value from a subquery
col LIKE 'ab%' Pattern: % any string, _ one character
col ILIKE 'ab%' Case-insensitive LIKE (PostgreSQL)
col ~ '^ab[0-9]+$' POSIX regex match (PostgreSQL), ~* is case-insensitive
col IS NULL, col IS NOT NULL NULL checks, = NULL never matches
a IS DISTINCT FROM b NULL-safe inequality
a IS NOT DISTINCT FROM b NULL-safe equality
EXISTS (SELECT 1 FROM ...) True if the subquery returns any row
col = ANY (ARRAY[1, 2]) Compare to any array element

Joins#

SELECT o.id, c.name
FROM orders o
JOIN customers c ON c.id = o.customer_id;
Join Result
INNER JOIN (or JOIN) Only rows matching in both tables
LEFT JOIN All left rows, NULLs where right has no match
RIGHT JOIN All right rows, NULLs where left has no match
FULL JOIN All rows from both sides
CROSS JOIN Cartesian product
JOIN ... USING (col) Join on equal columns with the same name, col appears once
NATURAL JOIN Join on all columns with the same name (avoid, fragile)
JOIN LATERAL (subquery) ON true Subquery that can reference earlier FROM items

Aggregation#

Syntax Description
COUNT(*) Number of rows
COUNT(col) Number of non-NULL values
COUNT(DISTINCT col) Number of distinct non-NULL values
SUM(col), AVG(col), MIN(col), MAX(col) Basic aggregates, they ignore NULLs
STRING_AGG(col, ', ' ORDER BY col) Concatenate values into one string
ARRAY_AGG(col) Collect values into an array
COUNT(*) FILTER (WHERE cond) Aggregate only rows matching cond
GROUP BY ROLLUP (a, b) Subtotals and grand total
GROUP BY CUBE (a, b) Subtotals for every combination
GROUP BY GROUPING SETS ((a), (b)) Explicit list of groupings

WHERE filters rows before grouping, HAVING filters groups after it.

Window functions#

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_avg
FROM employees;
Function Description
ROW_NUMBER() Unique sequential number in the partition
RANK() Rank with gaps after ties
DENSE_RANK() Rank without gaps
NTILE(n) Split the partition into n buckets
LAG(col, 1) / LEAD(col, 1) Value from the previous / next row
FIRST_VALUE(col) / LAST_VALUE(col) First / last value in the frame
SUM(col) OVER (ORDER BY d) Running total
... ROWS BETWEEN 2 PRECEDING AND CURRENT ROW Explicit window frame

Combining results#

Syntax Description
query1 UNION query2 Rows from both, duplicates removed
query1 UNION ALL query2 Rows from both, duplicates kept (faster)
query1 INTERSECT query2 Rows present in both
query1 EXCEPT query2 Rows in the first but not in the second

Both queries need the same number of columns with compatible types.

CTEs and subqueries#

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.total
FROM recent_orders r
JOIN 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;

Inserting, updating, deleting#

INSERT INTO users (name, email)
VALUES ('Ann', 'ann@example.com'), ('Bob', 'bob@example.com')
RETURNING id;

INSERT INTO users (email, name)
VALUES ('ann@example.com', 'Ann B.')
ON CONFLICT (email) DO UPDATE SET name = EXCLUDED.name;

UPDATE users SET active = false WHERE last_login < now() - interval '1 year';

UPDATE orders o
SET status = 'paid'
FROM payments p
WHERE p.order_id = o.id;

DELETE FROM sessions WHERE expires_at < now();

TRUNCATE TABLE logs RESTART IDENTITY;
Syntax Description
RETURNING cols Return affected rows from INSERT, UPDATE, DELETE
ON CONFLICT DO NOTHING Ignore rows that violate a unique constraint
ON CONFLICT (col) DO UPDATE SET ... Upsert
INSERT INTO t SELECT ... Insert the result of a query
UPDATE ... FROM other Update using values from another table
DELETE FROM t USING other WHERE ... Delete using another table
MERGE INTO t USING s ON ... WHEN MATCHED ... Standard upsert (PostgreSQL 15+)
TRUNCATE Remove all rows quickly, no WHERE allowed

UPDATE and DELETE without WHERE affect every row. Run them inside a transaction first.

Defining tables#

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

Constraints#

Constraint Description
PRIMARY KEY Unique and NOT NULL, one per table
UNIQUE No duplicate values, NULLs are allowed (multiple)
NOT NULL Value is required
CHECK (expr) Value must satisfy the expression
REFERENCES t (c) Foreign key
ON DELETE CASCADE Delete referencing rows too
ON DELETE SET NULL Set the referencing column to NULL
ON DELETE RESTRICT Forbid deleting a referenced row
DEFERRABLE INITIALLY DEFERRED Check the constraint at commit, not per statement

Data types#

Type Notes
smallint, integer, bigint 2, 4, 8 byte integers
numeric(p, s) Exact decimal, use for money
real, double precision Floating point, inexact
text Unlimited string, same performance as varchar(n)
varchar(n), char(n) Length-limited strings
boolean true, false, NULL
date, time, timestamp Without time zone
timestamptz Timestamp with time zone, usually the right choice
interval Time span, for example interval '1 day'
uuid UUID, generate with gen_random_uuid()
jsonb Binary JSON, indexable
json JSON stored as text
type[] Arrays, for example int[]
bytea Binary data
inet, cidr IP addresses and networks
enum CREATE TYPE mood AS ENUM ('sad', 'ok', 'happy')

Common functions#

Group Syntax Description
Null handling COALESCE(a, b, c) First non-NULL argument
Null handling NULLIF(a, b) NULL if a = b, otherwise a
Conditional CASE WHEN c THEN x ELSE y END Conditional expression
Cast col::integer, CAST(col AS integer) Type conversion
String a || b Concatenation
String LENGTH(s), LOWER(s), UPPER(s) Basics
String TRIM(s), LTRIM(s), RTRIM(s) Strip whitespace
String SUBSTRING(s FROM 2 FOR 3) Substring
String REPLACE(s, 'a', 'b') Replace occurrences
String SPLIT_PART(s, ',', 2) N-th piece of a delimited string
String FORMAT('%s has %s', a, b) Printf-style formatting
Math ROUND(x, 2), CEIL(x), FLOOR(x) Rounding
Math ABS(x), MOD(a, b), POWER(a, b) Basics
Date now(), CURRENT_DATE Current timestamp and date
Date date_trunc('month', ts) Truncate to a unit
Date EXTRACT(year FROM ts) Pull out a part of a date
Date ts + interval '2 days' Date arithmetic
Date age(ts1, ts2) Difference as an interval
Date to_char(ts, 'YYYY-MM-DD HH24:MI') Format a timestamp
Series generate_series(1, 10) Set of numbers (also works for dates)

JSON#

Syntax Description
data -> 'key' Get a field as jsonb
data ->> 'key' Get a field as text
data #> '{a,b}' Get a nested value by path as jsonb
data #>> '{a,b}' Get a nested value by path as text
data @> '{"a": 1}' Contains the given JSON
data ? 'key' Has the top-level key
jsonb_build_object('a', 1) Build an object
jsonb_agg(col) Aggregate rows into a JSON array
jsonb_array_elements(arr) Expand an array into rows
jsonb_set(data, '{a}', '2') Set a value at a path
CREATE INDEX ON t USING gin (data) Index for @> and ? queries

Transactions#

BEGIN;
UPDATE accounts SET balance = balance - 100 WHERE id = 1;
UPDATE accounts SET balance = balance + 100 WHERE id = 2;
COMMIT;
Syntax Description
BEGIN / START TRANSACTION Start a transaction
COMMIT Save changes
ROLLBACK Discard changes
SAVEPOINT sp Mark a point inside a transaction
ROLLBACK TO SAVEPOINT sp Undo back to the savepoint
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE Choose an isolation level (READ COMMITTED is the default)

Analysing queries#

Syntax Description
EXPLAIN query Show the planned execution
EXPLAIN ANALYZE query Run the query and show actual timings (it really executes, wrap UPDATE in a transaction you roll back)
EXPLAIN (ANALYZE, BUFFERS) query Also show buffer usage
ANALYZE t Refresh planner statistics
VACUUM (VERBOSE) t Reclaim space from dead rows

Permissions#

Syntax Description
CREATE ROLE app LOGIN PASSWORD '...' Create a user
GRANT SELECT, INSERT ON t TO app Grant table privileges
GRANT ALL ON ALL TABLES IN SCHEMA public TO app Grant on every table in a schema
REVOKE INSERT ON t FROM app Remove a privilege
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO app Privileges for future tables
ALTER ROLE app PASSWORD '...' Change a password
DROP ROLE app Delete a role