BTI Beyond The Interviews

Languages · 13 sections

SQL

Joins, aggregations, window functions, and the SQL interview essentials.

Free · full sheet 114 cards Updated 24 Oct 2026

Basics

SELECT / FROM / WHERE

SELECT columns FROM table WHERE condition. WHERE filters rows before grouping. Use * sparingly; list columns for clarity and performance.

SELECT id, name, email
FROM users
WHERE active = true AND created_at >= '2024-01-01';

ORDER BY

Sort result set. ASC (default) / DESC. Multiple columns: ORDER BY dept ASC, salary DESC. NULLS FIRST/LAST controls null placement (Postgres/Oracle; MySQL emulates with IS NULL).

SELECT name, salary
FROM employees
ORDER BY dept ASC, salary DESC NULLS LAST;

DISTINCT

Removes duplicate rows from result. DISTINCT ON (col) (Postgres) keeps the first row per group according to ORDER BY. DISTINCT is not free—it sorts or hashes; consider GROUP BY or a semi-join when you only need existence.

SELECT DISTINCT dept FROM employees;

-- Postgres: latest row per user
SELECT DISTINCT ON (user_id) user_id, created_at
FROM orders
ORDER BY user_id, created_at DESC;

LIMIT / OFFSET and keyset pagination

LIMIT n returns n rows; OFFSET skips. Standard SQL: FETCH FIRST n ROWS ONLY. Deep OFFSET is slow because the engine still scans and discards the skipped rows. Prefer keyset pagination: WHERE (created_at, id) < (:last_created_at, :last_id) ORDER BY created_at DESC, id DESC LIMIT n, which is stable under inserts and uses the index.

SELECT id, created_at
FROM orders
ORDER BY created_at DESC, id DESC
LIMIT 20 OFFSET 400;  -- page 21: scans 400 rows it throws away

SELECT id, created_at
FROM orders
WHERE (created_at, id) < ('2024-05-01', 9042)
ORDER BY created_at DESC, id DESC
LIMIT 20;  -- keyset: index seek, constant cost

Aliases

Column/table aliases with AS (AS optional for tables). Use for readability and self-joins. Alias can be used in ORDER BY in most DBs, not WHERE (WHERE runs before SELECT).

SELECT u.name AS user_name, o.total * 2 AS double_total
FROM users AS u
JOIN orders AS o ON o.user_id = u.id
ORDER BY double_total DESC;

LIKE / ILIKE

% matches any sequence, _ matches single char. ILIKE is case-insensitive (Postgres). Escape wildcards with ESCAPE. Index-friendly only with prefix patterns (col LIKE 'abc%'); leading wildcards force a scan unless you use a trigram index.

SELECT id FROM users WHERE email ILIKE 'ada@%';
SELECT id FROM docs WHERE title LIKE '100\% done' ESCAPE '\';

IN / BETWEEN

IN (list/subquery) membership. BETWEEN is inclusive both ends: x BETWEEN a AND b ⇔ x >= a AND x <= b. NOT IN with NULLs yields no rows—use NOT EXISTS. Neither is sargable-hostile: both are index-friendly with plain literals.

SELECT * FROM orders
WHERE status IN ('paid', 'shipped')
  AND created_at BETWEEN '2024-01-01' AND '2024-03-31';

CASE expression

Conditional logic. Simple: CASE col WHEN val THEN ... END. Searched: CASE WHEN cond THEN ... END. Use in SELECT, WHERE, ORDER BY, GROUP BY. CASE evaluates conditions in order and returns the first match.

SELECT name,
  CASE WHEN salary > 100000 THEN 'high'
       WHEN salary > 50000 THEN 'mid'
       ELSE 'low' END AS band
FROM employees;

String functions

CONCAT, SUBSTRING, LENGTH/CHAR_LENGTH, UPPER/LOWER, TRIM, REPLACE, POSITION/INSTR. || concatenation (Postgres/Oracle/SQLite); + in SQL Server (and || since 2025). CONCAT treats NULL as empty string; || returns NULL if any argument is NULL.

SELECT UPPER(TRIM(first_name)) || ' ' || last_name AS full_name,
       LENGTH(email) AS email_len,
       REPLACE(phone, '-', '') AS digits
FROM users;

Date functions

CURRENT_DATE, NOW()/CURRENT_TIMESTAMP. DATE_TRUNC, EXTRACT(YEAR FROM d), DATEADD/DATEDIFF (SQL Server). Store in UTC (timestamptz in Postgres); convert at presentation. Avoid applying functions to indexed date columns in predicates.

SELECT DATE_TRUNC('month', created_at) AS month,
       COUNT(*) AS signups
FROM users
WHERE created_at >= '2024-01-01'
GROUP BY 1
ORDER BY 1;

COALESCE / NULLIF

COALESCE(a, b, ...) returns the first non-NULL argument; NULLIF(a, b) returns NULL when a = b (classic use: avoid divide-by-zero). COALESCE generally short-circuits, but don't rely on it with side-effecting or volatile arguments—evaluation order is not guaranteed across engines.

SELECT revenue / NULLIF(units, 0) AS price_per_unit,
  COALESCE(nickname, first_name, 'anon') AS display_name
FROM users;

JSON columns

Postgres json/jsonb (jsonb is binary, indexable and the default choice), MySQL JSON, SQL Server JSON stored as nvarchar. Operators: -> returns JSON, ->> returns text; #>> path. Query with containment (@>, jsonb_path_exists) rather than extracting in WHERE, and index with GIN (jsonb_path_ops for @>). JSON is for sparse, evolving attributes—not for columns you filter and join on routinely.

SELECT id, payload->>'name' AS name, payload#>>'{address,city}' AS city
FROM events
WHERE payload @> '{"type": "signup"}';

CREATE INDEX idx_events_payload ON events USING gin (payload jsonb_path_ops);

SQL injection and parameterization

SQL injection happens when untrusted input is concatenated into SQL. Use parameterized queries / prepared statements ($1 in Postgres, ? in MySQL/SQLite, @p1 in SQL Server) so values travel out-of-band and are never parsed as SQL. Never build queries with string interpolation. Identifiers (table/column names) cannot be parameterized—map them through an allowlist. Also apply least-privilege DB roles and escape LIKE wildcards. ORMs help only if you avoid raw string interpolation.

-- NEVER: input becomes SQL
-- "SELECT * FROM users WHERE email = '" + email + "'"

-- Parameterized (Postgres): value is sent separately from the statement
PREPARE find_user (text) AS
  SELECT id, email FROM users WHERE email = $1;
EXECUTE find_user('ada@example.com');

-- MySQL / SQLite: ?
-- SELECT id FROM users WHERE email = ?;

Joins

INNER JOIN

Returns rows matching in both tables. Most common. Use when you only want matched records.

SELECT u.name, o.total
FROM users u
INNER JOIN orders o ON u.id = o.user_id;

LEFT / RIGHT JOIN

LEFT: all rows from left + matched from right (NULL if no match). RIGHT: opposite. Prefer LEFT JOIN for 'all X even without Y'. Filtering the right table in WHERE silently turns it into an inner join—put that predicate in ON.

SELECT u.id, u.name, o.total
FROM users u
LEFT JOIN orders o
  ON o.user_id = u.id AND o.status = 'paid'
WHERE u.created_at >= '2024-01-01';

FULL OUTER JOIN

All rows from both tables, matched where possible; NULLs for unmatched. Use for reconciliation and finding mismatches. MySQL has no FULL OUTER JOIN—emulate with LEFT UNION ALL RIGHT anti-rows.

SELECT a.id AS a_id, b.id AS b_id
FROM a
FULL OUTER JOIN b ON a.id = b.id
WHERE a.id IS NULL OR b.id IS NULL;  -- rows present on one side only

CROSS JOIN

Cartesian product: every row × every row. Use for generating combinations, date series, or test data. Avoid accidental (missing ON).

SELECT d.day, s.region
FROM generate_series('2024-01-01'::date, '2024-01-07', '1 day') AS d(day)
CROSS JOIN regions s;

Self join

Join a table to itself with aliases. Used for hierarchical data (employee-manager) or comparing rows within same table.

SELECT e.name AS emp, m.name AS mgr
FROM employees e
LEFT JOIN employees m ON e.manager_id = m.id;

Anti-join

Rows in A not in B. Use LEFT JOIN ... WHERE B.id IS NULL, or NOT EXISTS (safe with NULLs), or EXCEPT. NOT IN fails if B contains NULLs.

SELECT u.* FROM users u
WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.user_id = u.id);

Semi-join

Rows in A that have a match in B (existence). Use EXISTS or IN. Returns A columns only; no duplication from multiple B matches. Optimizers execute IN/EXISTS as semi-joins.

SELECT u.id, u.name
FROM users u
WHERE EXISTS (SELECT 1 FROM orders o WHERE o.user_id = u.id);

Join conditions

ON for join predicate; WHERE for filtering. For inner joins, ON vs WHERE equivalent. For outer joins, filtering in WHERE converts to inner (move to ON to keep unmatched).

-- keeps users with no paid orders
SELECT u.id, o.id
FROM users u
LEFT JOIN orders o ON o.user_id = u.id AND o.status = 'paid';

-- returns only users who have a paid order
SELECT u.id, o.id
FROM users u
LEFT JOIN orders o ON o.user_id = u.id
WHERE o.status = 'paid';

Multiple joins

Chain joins; optimizer reorders. Keep join order readable. Use table aliases consistently. Check cardinality to avoid row explosion (many-to-many fan-out inflates SUM/COUNT).

SELECT u.id, COUNT(DISTINCT o.id) AS orders, COUNT(DISTINCT t.id) AS tickets
FROM users u
LEFT JOIN orders o ON o.user_id = u.id
LEFT JOIN tickets t ON t.user_id = u.id
GROUP BY u.id;  -- DISTINCT prevents fan-out double counting

Join performance

Index the join columns on both sides. Hash join for large unsorted inputs; merge join for pre-sorted inputs; nested loop for small outer sets or indexed inner lookups. Keep statistics fresh so the planner picks correctly.

EXPLAIN (ANALYZE, BUFFERS)
SELECT u.id, o.total
FROM users u JOIN orders o ON o.user_id = u.id
WHERE u.id = 42;  -- expect nested loop + index scan on orders(user_id)

USING / NATURAL JOIN

USING (col) joins on a common column and outputs it once. NATURAL JOIN auto-joins on all same-named columns—avoid (fragile: adding an unrelated id column changes the join).

SELECT id, name
FROM users
JOIN profiles USING (id);  -- id appears once in the output

Set Operations

UNION vs UNION ALL

UNION concatenates and removes duplicates (sort or hash); UNION ALL concatenates and keeps duplicates. UNION ALL is faster and preserves multiplicity—use it unless deduplication is required. Both require the same number of columns with compatible types; column names come from the first query.

SELECT email FROM customers
UNION ALL
SELECT email FROM leads;  -- keeps duplicate emails

SELECT email FROM customers
UNION
SELECT email FROM leads;  -- deduplicates

INTERSECT / EXCEPT

INTERSECT returns distinct rows present in both inputs; EXCEPT (MINUS in Oracle) returns distinct rows in the first but not the second. Both deduplicate; INTERSECT ALL / EXCEPT ALL keep multiplicity (Postgres 15+, SQL Server; MySQL 8.0.31+ supports INTERSECT/EXCEPT but not the ALL forms).

SELECT user_id FROM orders
INTERSECT
SELECT user_id FROM trials;  -- converted and trialled

SELECT user_id FROM trials
EXCEPT
SELECT user_id FROM orders;  -- trialled, never bought

Set operation rules

Column count and compatible types must match; matching is positional, not by name. One ORDER BY / LIMIT applies to the whole result and goes at the end. INTERSECT binds tighter than UNION/EXCEPT—parenthesise when mixing. Set ops compare whole rows, so NULLs are treated as equal for duplicate elimination.

(SELECT id FROM a
 UNION
 SELECT id FROM b)
EXCEPT
SELECT id FROM c
ORDER BY id
LIMIT 100;

Set ops vs joins

Set operations stack rows; joins combine columns. UNION deduplicates whereas a join can multiply rows. INTERSECT/EXCEPT express 'in both' / 'in one but not the other' more readably than self-joins, and they compare entire rows—use EXISTS when you need extra columns from the other table.

-- same result, different intent
SELECT id FROM a INTERSECT SELECT id FROM b;

SELECT DISTINCT a.id
FROM a JOIN b ON b.id = a.id;

Aggregation

GROUP BY & HAVING

GROUP BY forms groups; aggregate with COUNT, SUM, AVG, MIN, MAX. WHERE filters rows before grouping and cannot use aggregates; HAVING filters groups after aggregation and can. Filter early in WHERE—it reduces the rows the aggregates must process—and reserve HAVING for conditions on aggregate results.

SELECT dept, COUNT(*) AS n, AVG(salary) AS avg_sal
FROM employees
WHERE active = true          -- rows
GROUP BY dept
HAVING COUNT(*) > 5          -- groups
ORDER BY avg_sal DESC;

COUNT variations

COUNT(*) counts all rows. COUNT(col) counts non-NULL values. COUNT(DISTINCT col) counts distinct non-NULL values. COUNT(1) is the same as COUNT(*). COUNT(DISTINCT a, b) (Postgres/MySQL) counts distinct pairs.

SELECT COUNT(*) AS rows,
       COUNT(manager_id) AS has_manager,
       COUNT(DISTINCT dept_id) AS depts
FROM employees;

SUM / AVG / MIN / MAX (NULLs and empty sets)

All aggregates ignore NULLs: AVG = SUM(non-null) / COUNT(non-null), and MIN/MAX skip NULLs. Over an empty set (or all-NULL input) SUM/AVG/MIN/MAX return NULL while COUNT returns 0. That is why reports use COALESCE(SUM(x), 0) but usually leave AVG as NULL to signal 'no data'. Use COUNT(*) - COUNT(col) to count NULLs.

SELECT COALESCE(SUM(amount), 0) AS total,
       AVG(amount) AS avg_amount,       -- NULL when there are no rows
       COUNT(*) - COUNT(amount) AS null_amounts
FROM payments
WHERE user_id = 42;

GROUP BY rules

Non-aggregated SELECT columns must appear in GROUP BY (standard SQL). Functional dependencies (Postgres) allow omitting columns functionally determined by the PK. GROUP BY 1,2 positional shorthand works but breaks when the SELECT list changes—prefer names.

SELECT dept, job, COUNT(*)
FROM employees
GROUP BY dept, job;

ROLLUP / CUBE / GROUPING SETS

ROLLUP: hierarchical subtotals (a,b) then (a) then (). CUBE: all combinations. GROUPING SETS: explicit list. Use GROUPING(col) to distinguish a subtotal NULL from a data NULL. Supported in Postgres, SQL Server, Oracle, MySQL 8 (no CUBE/ROLLUP in older MySQL).

SELECT dept, job, SUM(sal) AS total,
       GROUPING(dept) AS is_dept_subtotal
FROM emp
GROUP BY ROLLUP (dept, job);

FILTER clause

Aggregate with a condition: COUNT(*) FILTER (WHERE status = 'active'). Cleaner and usually faster than CASE inside the aggregate, and it keeps the aggregate's NULL handling intact. Postgres/SQLite/standard; SQL Server and MySQL use conditional SUM(CASE WHEN ... THEN 1 END).

SELECT user_id,
  COUNT(*) FILTER (WHERE status = 'paid')     AS paid,
  COUNT(*) FILTER (WHERE status = 'refunded') AS refunded,
  COUNT(*) FILTER (WHERE status = 'paid') * 1.0 / COUNT(*) AS paid_rate
FROM orders
GROUP BY user_id;

String aggregation

Postgres: STRING_AGG(col, ', ' ORDER BY col). MySQL: GROUP_CONCAT(col ORDER BY col SEPARATOR ', '). SQL Server: STRING_AGG(col, ',') WITHIN GROUP (ORDER BY col). Oracle: LISTAGG(col, ', ') WITHIN GROUP (ORDER BY col). Ordering is part of each dialect's syntax—WITHIN GROUP alone is not portable. MySQL caps GROUP_CONCAT at group_concat_max_len.

-- Postgres
SELECT dept, STRING_AGG(name, ', ' ORDER BY name) AS members
FROM employees
GROUP BY dept;

-- MySQL
-- SELECT dept, GROUP_CONCAT(name ORDER BY name SEPARATOR ', ')
-- FROM employees GROUP BY dept;

Percentiles

PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY x) interpolates (continuous); PERCENTILE_DISC returns an actual value. Median = 0.5 percentile. Postgres/SQL Server/Oracle support both; MySQL 8 lacks them—use NTILE or a windowed row_number. MODE() WITHIN GROUP (ORDER BY x) (Postgres/Oracle) returns the most frequent value.

SELECT PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY salary) AS median,
       PERCENTILE_CONT(0.9) WITHIN GROUP (ORDER BY salary) AS p90,
       MODE() WITHIN GROUP (ORDER BY dept) AS modal_dept
FROM employees;

Subqueries

Scalar subquery

Returns a single value; usable in SELECT/WHERE. Must return at most one row/column (more than one row is a runtime error). If no rows → NULL. Correlated scalar subqueries can be slow per outer row.

SELECT name,
       (SELECT MAX(salary) FROM employees e2 WHERE e2.dept = e.dept) AS dept_max
FROM employees e;

Row subquery

Returns one row with multiple columns: WHERE (a,b) = (SELECT x,y FROM ...). Compare tuples; (a,b) IN (SELECT x,y ...) also works and is useful for composite keys.

SELECT * FROM orders
WHERE (user_id, created_at) = (
  SELECT user_id, MAX(created_at) FROM orders GROUP BY user_id LIMIT 1
);

Table subquery (derived table)

Subquery in FROM: SELECT ... FROM (SELECT ...) t. Must alias (MySQL requires it). Use to pre-aggregate or simplify. A CTE is often clearer and can be reused.

SELECT t.dept, t.avg_salary
FROM (SELECT dept, AVG(salary) AS avg_salary
      FROM employees GROUP BY dept) AS t
WHERE t.avg_salary > 80000;

Correlated subquery

References outer query columns; conceptually re-evaluated per outer row. Powerful but can be slow; often rewritable as a JOIN or window function. Check EXPLAIN for repeated inner scans.

SELECT e.name,
  (SELECT AVG(salary) FROM employees WHERE dept = e.dept) AS dept_avg
FROM employees e;

EXISTS

Tests whether the subquery returns any row, stopping at the first match. Modern optimizers plan EXISTS and IN as the same semi-join, so neither is inherently faster on large datasets. The real difference is NULL semantics: NOT EXISTS is safe when the subquery can produce NULLs, while NOT IN returns no rows at all if it can.

SELECT u.id, u.name
FROM users u
WHERE EXISTS (
  SELECT 1 FROM orders o WHERE o.user_id = u.id AND o.total > 100
);

IN vs JOIN

IN (subquery) expresses a semi-join: at most one output row per left row. JOIN can duplicate rows when the right side has multiple matches, so it needs DISTINCT or GROUP BY. Prefer EXISTS/IN for 'has a match', JOIN when you need columns from the other table.

-- one row per user, even with many orders
SELECT id FROM users
WHERE id IN (SELECT user_id FROM orders);

-- duplicates users with multiple orders
SELECT u.id FROM users u JOIN orders o ON o.user_id = u.id;

ANY / ALL

col > ANY (subquery) is true if any row satisfies; col > ALL is true only if all rows do. = ANY is equivalent to IN; <> ALL is equivalent to NOT IN (and inherits the NULL pitfall). Empty subquery: ANY → false, ALL → true.

SELECT * FROM products
WHERE price > ALL (SELECT price FROM products WHERE category = 'budget');

SELECT * FROM products
WHERE category = ANY (ARRAY['books', 'music']);

Subquery in SELECT

Scalar subquery evaluated per row. Can cause N+1-like execution; prefer a join to a pre-aggregated derived table or a window function for aggregates.

SELECT o.id,
       (SELECT COUNT(*) FROM items i WHERE i.order_id = o.id) AS item_count
FROM orders o;

Lateral / CROSS APPLY

LATERAL (Postgres) / CROSS APPLY (SQL Server) lets a FROM-clause subquery reference columns from preceding tables. Use for top-N per group, correlated derived tables, and set-returning functions. LEFT JOIN LATERAL ... ON true keeps groups with no matches.

SELECT d.name, t.*
FROM departments d
CROSS JOIN LATERAL (
  SELECT * FROM employees e
  WHERE e.dept_id = d.id ORDER BY salary DESC LIMIT 3
) t;

Subquery flattening

Optimizers often merge subqueries into joins (flattening); correlated subqueries may stay as loops. IN/EXISTS become semi-joins, NOT IN/NOT EXISTS become anti-joins. Check EXPLAIN before rewriting by hand.

EXPLAIN
SELECT * FROM users u
WHERE EXISTS (SELECT 1 FROM orders o WHERE o.user_id = u.id);
-- look for: Hash Semi Join / Nested Loop Semi Join

Window Functions

Window function basics

Compute over a set of rows related to the current row without collapsing them (unlike GROUP BY). OVER (PARTITION BY ... ORDER BY ...). Runs after WHERE/GROUP BY/HAVING, before ORDER BY/LIMIT.

SELECT name, dept, salary,
  ROW_NUMBER() OVER (PARTITION BY dept ORDER BY salary DESC) AS rn
FROM employees;

ROW_NUMBER / RANK / DENSE_RANK

ROW_NUMBER: unique sequential (arbitrary on ties unless ORDER BY is unique). RANK: ties share a rank, then gaps. DENSE_RANK: ties share a rank, no gaps. Use for top-N, dedup, pagination.

SELECT name, salary,
  ROW_NUMBER() OVER (ORDER BY salary DESC) AS rn,
  RANK()       OVER (ORDER BY salary DESC) AS rnk,
  DENSE_RANK() OVER (ORDER BY salary DESC) AS drnk
FROM employees;

LAG / LEAD

Access a previous/next row's value within the partition. LAG(col, offset, default). Used for deltas, comparisons, running calculations. Requires a deterministic ORDER BY.

SELECT date, revenue,
  revenue - LAG(revenue, 1, 0) OVER (ORDER BY date) AS delta
FROM sales;

NTILE

Divides the partition into n buckets as evenly as possible; assigns bucket numbers. Useful for quartiles/deciles and equal-size cohorts. Unlike percentile_cont, it does not interpolate.

SELECT name, salary,
  NTILE(4) OVER (ORDER BY salary DESC) AS quartile
FROM employees;

FIRST_VALUE / LAST_VALUE / NTH_VALUE

Return the first/last/nth value in the window frame. LAST_VALUE with the default frame (up to current row) returns the current row—add ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING.

SELECT name,
  FIRST_VALUE(name) OVER (PARTITION BY dept ORDER BY salary DESC) AS top_earner,
  LAST_VALUE(name) OVER (
    PARTITION BY dept ORDER BY salary DESC
    ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
  ) AS lowest_earner
FROM employees;

Running totals

SUM(col) OVER (ORDER BY date) gives a running total. Add PARTITION BY for per-group. Default frame: RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW (peers share a value; use ROWS to accumulate row by row).

SELECT date, amount,
  SUM(amount) OVER (PARTITION BY account_id ORDER BY date
                    ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS balance
FROM transactions;

Window frames

ROWS (physical rows) vs RANGE (logical value peers). UNBOUNDED PRECEDING/FOLLOWING, CURRENT ROW, n PRECEDING/FOLLOWING. RANGE with dates/numbers interprets n as a value offset (RANGE BETWEEN INTERVAL '7 days' PRECEDING AND CURRENT ROW). Use ROWS for fixed-size windows with ties.

SELECT date, amount,
  SUM(amount) OVER (ORDER BY date
    RANGE BETWEEN INTERVAL '6 days' PRECEDING AND CURRENT ROW) AS trailing_7d
FROM sales;

Moving average

AVG(col) OVER (ORDER BY date ROWS BETWEEN 6 PRECEDING AND CURRENT ROW) = 7-row moving avg. Use ROWS for a fixed number of observations, RANGE for a fixed time span. Early rows average fewer observations.

SELECT date, revenue,
  AVG(revenue) OVER (ORDER BY date ROWS BETWEEN 6 PRECEDING AND CURRENT ROW) AS ma7
FROM sales;

Top-N per group

Use ROW_NUMBER() OVER (PARTITION BY group ORDER BY metric DESC) then filter rn <= N in an outer query (window functions are not allowed in WHERE). LATERAL is an alternative when N is large or indexed.

SELECT * FROM (
  SELECT *, ROW_NUMBER() OVER (PARTITION BY dept ORDER BY salary DESC) rn
  FROM employees
) t WHERE rn <= 3;

Dedup with window

ROW_NUMBER() OVER (PARTITION BY key ORDER BY updated_at DESC) then keep rn = 1. Cleaner than a correlated subquery and handles ties via ORDER BY. Delete with a CTE/derived table in Postgres, or a self-join on the row id in MySQL.

WITH ranked AS (
  SELECT id,
    ROW_NUMBER() OVER (PARTITION BY email ORDER BY updated_at DESC) AS rn
  FROM users
)
DELETE FROM users u USING ranked r
WHERE u.id = r.id AND r.rn > 1;

Gaps and islands

Classic pattern for consecutive runs (login streaks, unbroken date ranges). Number the rows within each partition, then subtract the row number from the sequence value: consecutive values yield a constant 'island key'. Group by that key. Use a date difference in Postgres or DATE_SUB(..., INTERVAL rn DAY) in MySQL. Gaps are simply the complement—the missing ranges between islands.

WITH numbered AS (
  SELECT user_id, login_date,
         login_date - (ROW_NUMBER() OVER (
           PARTITION BY user_id ORDER BY login_date
         ))::int AS island_key
  FROM logins
)
SELECT user_id,
       MIN(login_date) AS streak_start,
       MAX(login_date) AS streak_end,
       COUNT(*)        AS streak_days
FROM numbered
GROUP BY user_id, island_key
ORDER BY user_id, streak_start;

Window function restrictions

Cannot nest window functions or use them directly in WHERE/GROUP BY/HAVING—wrap in a subquery or CTE. Aggregate window functions (SUM OVER) are allowed. DISTINCT is not allowed inside most window functions. Named windows (WINDOW w AS (...)) reduce repetition.

SELECT * FROM (
  SELECT name, dept, SUM(salary) OVER (PARTITION BY dept) AS dept_payroll
  FROM employees
) t
WHERE dept_payroll > 500000;

DML & Upserts

INSERT / UPDATE / DELETE

INSERT INTO t (cols) VALUES (...); UPDATE changes existing rows (always use WHERE unless you mean all rows); DELETE removes rows and fires triggers. DML is transactional—wrap multi-statement changes in BEGIN/COMMIT and use RETURNING (Postgres) or OUTPUT (SQL Server) to get affected rows back in one round trip.

INSERT INTO users (email, name)
VALUES ('ada@example.com', 'Ada')
RETURNING id;

UPDATE accounts
SET balance = balance - 100
WHERE id = 1 AND balance >= 100
RETURNING balance;

DELETE FROM sessions WHERE expires_at < now();

Upsert: INSERT ... ON CONFLICT

Insert-or-update in one statement. Postgres/SQLite: ON CONFLICT (key) DO UPDATE SET ... with EXCLUDED for the proposed row, or DO NOTHING. MySQL: INSERT ... ON DUPLICATE KEY UPDATE. Requires a unique/exclusion constraint to detect the conflict. ON CONFLICT is atomic and concurrency-safe, unlike SELECT-then-INSERT.

INSERT INTO users (email, name, updated_at)
VALUES ('ada@example.com', 'Ada Lovelace', now())
ON CONFLICT (email) DO UPDATE
  SET name = EXCLUDED.name,
      updated_at = EXCLUDED.updated_at
RETURNING id;

MERGE

Standard SQL upsert/merge: MERGE INTO target USING source ON ... WHEN MATCHED THEN UPDATE ... WHEN NOT MATCHED THEN INSERT ... Supported by SQL Server, Oracle, DB2 and Postgres 15+. Statement-level and set-based, but it is not a substitute for ON CONFLICT in concurrent Postgres workloads (MERGE can raise serialization/duplicate errors under race). SQL Server's MERGE has known concurrency pitfalls—test with concurrent writers.

MERGE INTO inventory AS t
USING staging AS s ON t.sku = s.sku
WHEN MATCHED THEN
  UPDATE SET qty = t.qty + s.qty
WHEN NOT MATCHED THEN
  INSERT (sku, qty) VALUES (s.sku, s.qty);

DELETE vs TRUNCATE

DELETE removes rows row-by-row, can have WHERE, fires triggers, and is fully transactional. TRUNCATE is a bulk operation that deallocates storage, cannot filter rows, is much faster, and resets identity in some engines; it takes an ACCESS EXCLUSIVE lock in Postgres and cannot run when FKs reference the table. Use TRUNCATE for test resets and full reloads.

DELETE FROM logs WHERE created_at < now() - INTERVAL '90 days';

TRUNCATE TABLE staging_events;            -- all rows, fast
TRUNCATE TABLE staging_events RESTART IDENTITY;  -- Postgres: reset sequences

Indexes

What is an index

Auxiliary data structure (usually B-tree) to speed up lookups/joins/sorts. Trade-off: faster reads, slower writes, extra storage and vacuum/maintenance cost.

CREATE INDEX idx_orders_user_id ON orders (user_id);
-- speeds: WHERE user_id = 42, JOIN ... ON o.user_id = u.id

B-tree index

Balanced tree; supports equality, range, ORDER BY, and prefix matching. Default index type in most RDBMS. O(log n) lookup, with high fan-out so the tree stays shallow.

CREATE INDEX idx_orders_created_at ON orders (created_at);
-- serves: =, <, >, BETWEEN, ORDER BY created_at

Composite index

Index on multiple columns. Leftmost-prefix rule: (a,b,c) serves a, (a,b), (a,b,c) and ORDER BY on that prefix, but not b alone—though Postgres 18, MySQL 8.0.13+ and Oracle can skip-scan when the leading column has low cardinality. Order columns by query pattern: equality-filtered columns first, then range/sort columns. Selective-first is a weak heuristic—reuse of an existing index prefix matters more.

CREATE INDEX idx_orders_user_status_created
  ON orders (user_id, status, created_at);
-- equality columns first (user_id, status), then range/sort (created_at)
-- serves: user_id = ? AND status = ? ORDER BY created_at

Covering index

Index contains all columns needed by the query → index-only scan, no table heap lookup. INCLUDE columns (Postgres/SQL Server) add non-key payload columns that don't affect ordering; MySQL InnoDB implicitly includes the PK. An index-only scan still needs visibility info (Postgres: vacuum must have run).

CREATE INDEX idx_orders_user_cover
  ON orders (user_id) INCLUDE (total, created_at);

SELECT total, created_at FROM orders WHERE user_id = 42;  -- index-only

Clustered vs non-clustered

A clustered index determines physical row order (one per table; usually the PK in SQL Server and InnoDB). A non-clustered index is a separate structure whose entries point at rows (InnoDB: at the PK, so a secondary lookup costs a second traversal). Postgres has no clustered index—only CLUSTER, a one-off physical reorder.

-- SQL Server: clustered PK, non-clustered secondary
CREATE CLUSTERED INDEX ix_orders_id ON orders (id);
CREATE NONCLUSTERED INDEX ix_orders_user ON orders (user_id);

Hash index

O(1) equality lookups; no range, ordering or prefix support. Postgres hash indexes are WAL-logged and crash-safe since PG10. Hash joins do not use them—the executor builds its own in-memory hash table from the smaller input.

CREATE INDEX idx_users_email_hash ON users USING hash (email);
-- helps: WHERE email = 'ada@example.com'
-- useless: WHERE email > 'a' or ORDER BY email

Partial / filtered index

Index only a subset of rows: CREATE INDEX ... WHERE active = true. Smaller, cheaper to maintain, and effective for common filtered queries (SQL Server calls it a filtered index). The predicate must be implied by the query for the planner to use it.

CREATE INDEX idx_orders_open ON orders (created_at)
  WHERE status = 'open';

SELECT * FROM orders WHERE status = 'open' ORDER BY created_at;

Expression / functional index

Index on an expression: CREATE INDEX ON users (LOWER(email)). The query must use the same expression for the planner to match it. Useful for case-insensitive lookups and JSON field extraction (though GIN is usually better for JSON).

CREATE INDEX idx_users_lower_email ON users (LOWER(email));

SELECT id FROM users WHERE LOWER(email) = 'ada@example.com';

When not to index

Small tables, low-cardinality columns (boolean flags), write-heavy tables, columns rarely queried, or when the index costs more than it saves. Every index adds write amplification, disk, cache pressure and vacuum work. Drop unused indexes.

SELECT relname, indexrelname, idx_scan
FROM pg_stat_user_indexes
WHERE idx_scan = 0
ORDER BY pg_relation_size(indexrelid) DESC;

Index maintenance

Watch bloat/fragmentation; REINDEX CONCURRENTLY (Postgres 12+) or rebuild online. Run ANALYZE after large data changes so the planner has fresh statistics. Monitor index usage and drop unused ones. In Postgres, autovacuum also maintains visibility maps needed for index-only scans.

REINDEX INDEX CONCURRENTLY idx_orders_user_id;
ANALYZE orders;

Sargability

A predicate is sargable when the engine can use an index seek for it. Keep the indexed column bare: no functions or casts on it, no leading wildcards, no arithmetic wrapped around it. Rewrite DATE_TRUNC(col) = ... as a half-open range, and make sure parameter types match the column to avoid implicit casts (a typed mismatch can cast the column and kill the index).

-- sargable
WHERE created_at >= '2024-01-01'
  AND created_at <  '2024-02-01'

-- not sargable: function on the indexed column
WHERE DATE_TRUNC('month', created_at) = '2024-01-01'

-- not sargable: leading wildcard
WHERE email LIKE '%@example.com'

Transactions

ACID

Atomicity (all or nothing), Consistency (constraints preserved), Isolation (concurrent txns don't interfere), Durability (committed data persists). Implemented via WAL/redo logs, locks or MVCC, and constraint checks.

BEGIN;
UPDATE accounts SET balance = balance - 100 WHERE id = 1;
UPDATE accounts SET balance = balance + 100 WHERE id = 2;
COMMIT;  -- both or neither

BEGIN / COMMIT / ROLLBACK

BEGIN starts a transaction; COMMIT persists; ROLLBACK undoes. DDL often auto-commits (DBMS-dependent; Postgres is transactional for DDL, MySQL is not). Use explicit transactions for multi-statement consistency, and keep them short.

BEGIN;
UPDATE inventory SET qty = qty - 1 WHERE sku = 'A-1' AND qty > 0;
-- application checks rows affected
COMMIT;
-- or ROLLBACK;

Isolation levels

ANSI levels: Read Uncommitted, Read Committed, Repeatable Read, Serializable. Defaults differ: Postgres and Oracle use Read Committed; MySQL InnoDB uses Repeatable Read. In Postgres, Repeatable Read is snapshot isolation—it already prevents phantoms but allows write skew; Serializable (SSI) also prevents write skew and other serialization anomalies, at the cost of serialization failures you must retry (SQLSTATE 40001). MySQL Repeatable Read uses next-key/gap locks instead of MVCC-only. Oracle's Serializable is snapshot isolation, not SSI.

BEGIN ISOLATION LEVEL SERIALIZABLE;
-- ...
COMMIT;  -- may fail with 40001; retry the whole transaction

Phenomena

Dirty read: read uncommitted data. Non-repeatable read: same row returns different values. Phantom read: new rows appear between queries. Lost update: two writers overwrite each other. Write skew: two transactions read overlapping data and write disjoint rows, together violating a constraint neither violates alone—allowed under snapshot isolation, prevented by Serializable. Serializable prevents all of these.

-- write skew: on-call doctors must keep >= 2 on shift
-- T1 and T2 each see 2 on call, each goes off call -> 0 on call
BEGIN ISOLATION LEVEL SERIALIZABLE;  -- SSI aborts one of them
UPDATE doctors SET on_call = false WHERE id = 1;
COMMIT;

Locks

Shared (S) for reads, Exclusive (X) for writes. Row-level (SELECT ... FOR UPDATE) vs table-level. Deadlocks occur on circular waits; the DB detects them and rolls back one transaction. FOR UPDATE NOWAIT / SKIP LOCKED are useful for queues.

BEGIN;
SELECT * FROM accounts WHERE id = 1 FOR UPDATE;
UPDATE accounts SET balance = balance - 100 WHERE id = 1;
COMMIT;

Optimistic vs pessimistic

Pessimistic: lock rows upfront (FOR UPDATE) — simple, but blocks and risks deadlock under contention. Optimistic: version column, update WHERE version = old, check rows affected, retry on conflict — better for low-contention reads and stateless APIs. Choose by contention profile; optimistic needs a retry loop.

UPDATE accounts
SET balance = balance - 100,
    version = version + 1
WHERE id = 1 AND version = 7;
-- 0 rows affected => someone else won; re-read and retry

MVCC

Multi-Version Concurrency Control: readers see a snapshot; writers create new row versions. Enables high concurrency without read locks (Postgres, InnoDB, Oracle). Cost: old versions accumulate—Postgres needs VACUUM; long-running transactions delay cleanup.

SELECT xmin, xmax, * FROM accounts WHERE id = 1;
-- Postgres row version metadata (xmin = creating txn, xmax = deleting txn)

Savepoints

SAVEPOINT sp; ROLLBACK TO sp; partially undoes work inside a transaction. Useful for optional steps and for retry loops that cannot afford to restart the whole transaction.

BEGIN;
INSERT INTO orders (id) VALUES (1);
SAVEPOINT before_items;
INSERT INTO items (order_id, sku) VALUES (1, 'bad-sku');  -- fails
ROLLBACK TO before_items;
INSERT INTO items (order_id, sku) VALUES (1, 'A-1');
COMMIT;

Deadlock handling

Keep transactions short, access resources in a consistent order, use appropriate isolation, and index the predicates so locks are narrow. The application must retry on deadlock (Postgres SQLSTATE 40P01, serialization failure 40001; MySQL 1213).

-- retry loop (pseudo-code)
for attempt in 1..3:
  try: run_transaction(); break
  except Deadlock | SerializationFailure:
    backoff(attempt)

Autocommit

Each statement is its own transaction. Disable for multi-statement consistency. JDBC defaults to autocommit=true; set it false and commit explicitly. Many drivers and ORMs wrap work in a transaction per request.

-- psql: autocommit is on by default
\set AUTOCOMMIT off
BEGIN;  -- explicit control

Two-phase commit

Distributed transaction: prepare (vote) then commit. Ensures atomicity across databases, but is blocking, needs a coordinator, and can leave in-doubt transactions. Heavy; prefer sagas/outbox patterns for microservices.

PREPARE TRANSACTION 'tx-42';   -- Postgres 2PC
COMMIT PREPARED 'tx-42';

NULL Handling

Three-valued logic

SQL uses TRUE/FALSE/UNKNOWN. Any comparison with NULL yields UNKNOWN, and WHERE keeps only TRUE rows. NOT UNKNOWN is still UNKNOWN, so NOT (x = 1) does not return rows where x IS NULL—add OR x IS NULL explicitly. Use IS NULL / IS NOT NULL for null tests, never = NULL.

SELECT NULL = NULL AS eq,      -- NULL
       NULL IS NULL AS is_null, -- true
       NOT (NULL = 1) AS neg;   -- NULL

-- does not include rows where x IS NULL
SELECT * FROM t WHERE NOT (x = 1);

NULL-safe equality and joins

NULLs never match in = comparisons, so joins on nullable keys silently drop rows. NULL-safe operators: Postgres/standard IS [NOT] DISTINCT FROM; MySQL <=>; SQLite IS. SQL Server 2022+ supports IS [NOT] DISTINCT FROM (earlier versions need (a = b OR (a IS NULL AND b IS NULL))). Coalescing to a sentinel is the fallback.

SELECT * FROM a
JOIN b ON a.k IS NOT DISTINCT FROM b.k;

-- MySQL
-- SELECT * FROM a JOIN b ON a.k <=> b.k;

NULL in UNIQUE constraints

The standard treats NULLs as distinct, so a UNIQUE column allows multiple NULLs (Postgres, MySQL, SQLite, Oracle). SQL Server allows only one NULL per unique column. PostgreSQL 15+ lets you opt in to the strict behavior with UNIQUE NULLS NOT DISTINCT (also on CREATE UNIQUE INDEX). For one-NULL-per-group semantics elsewhere, use a partial unique index.

CREATE TABLE t (
  email text UNIQUE NULLS NOT DISTINCT  -- Postgres 15+
);

CREATE UNIQUE INDEX ux_t_email ON t (email) NULLS NOT DISTINCT;
-- or, portable: enforce with a partial unique index
CREATE UNIQUE INDEX ux_one_primary ON phones (user_id) WHERE is_primary;

NULL in ORDER BY

Null placement is engine-dependent: Postgres treats NULLs as larger than any value (NULLS LAST for ASC, NULLS FIRST for DESC); MySQL sorts NULLs first for ASC; SQL Server treats them as smallest. Specify NULLS FIRST/LAST for deterministic ordering (MySQL emulates with ORDER BY col IS NULL, col).

SELECT * FROM employees
ORDER BY manager_id NULLS LAST;

-- MySQL equivalent
-- ORDER BY manager_id IS NULL, manager_id

NULL in CASE

CASE col WHEN NULL ... never matches (NULL = NULL is UNKNOWN). Use the searched form: CASE WHEN col IS NULL THEN ... END. The same pitfall applies to simple CASE with NULL-producing expressions.

SELECT CASE
         WHEN manager_id IS NULL THEN 'top'
         ELSE 'reports'
       END AS level
FROM employees;

NULL and GROUP BY / DISTINCT

GROUP BY puts all NULLs in one group, and DISTINCT treats NULLs as equal—so DISTINCT returns a single NULL row. Aggregates then ignore those NULL values (COUNT(col) excludes them). Use COALESCE in the grouping expression if you want NULL reported as a label.

SELECT COALESCE(manager_id, -1) AS mgr, COUNT(*)
FROM employees
GROUP BY COALESCE(manager_id, -1);

NOT IN vs NOT EXISTS with NULLs

NOT IN (subquery) returns no rows at all if the subquery produces a single NULL, because x <> NULL is UNKNOWN and the AND chain never becomes TRUE. NOT EXISTS is NULL-safe and is the correct anti-join. Add IS NOT NULL inside the subquery only if you truly want NOT IN semantics. This—not performance—is the real reason to prefer NOT EXISTS.

-- returns 0 rows if any orders.user_id is NULL
SELECT * FROM users
WHERE id NOT IN (SELECT user_id FROM orders);

-- correct anti-join
SELECT * FROM users u
WHERE NOT EXISTS (
  SELECT 1 FROM orders o WHERE o.user_id = u.id
);

CTEs

WITH clause (CTE)

Named subquery for readability. WITH cte AS (...) SELECT ... FROM cte. Scope: a single statement. Can define multiple CTEs separated by commas. In Postgres 12+ CTEs are inlined by default unless recursive or used more than once.

WITH active_users AS (
  SELECT * FROM users WHERE active = true
)
SELECT * FROM active_users WHERE created_at > '2024-01-01';

CTE vs subquery

CTEs improve readability, allow reuse within the statement, and support recursion. They may be materialized or inlined depending on the engine and version. Use a CTE for multi-step logic; use a plain subquery for a one-off filter to keep the plan simple.

WITH paid AS (
  SELECT user_id, SUM(total) AS revenue
  FROM orders WHERE status = 'paid' GROUP BY user_id
)
SELECT u.name, p.revenue
FROM users u JOIN paid p ON p.user_id = u.id
WHERE p.revenue > 1000;

Recursive CTE

WITH RECURSIVE for hierarchical/tree data. Anchor member UNION ALL recursive member. Must terminate (depth limit or no new rows). Recursion is iterative, not stack-based, but cycles loop forever without a guard.

WITH RECURSIVE tree AS (
  SELECT id, parent_id, 1 AS depth FROM nodes WHERE parent_id IS NULL
  UNION ALL
  SELECT n.id, n.parent_id, t.depth + 1
  FROM nodes n JOIN tree t ON n.parent_id = t.id
)
SELECT * FROM tree;

Recursive CTE cycle safety

Prevent infinite loops with a depth counter or a visited-path array. Postgres 14+ has CYCLE ... SET ... USING PATH (and SEARCH BREADTH/DEPTH FIRST). Otherwise rely on acyclic data or add WHERE depth < n.

WITH RECURSIVE tree AS (
  SELECT id, parent_id, ARRAY[id] AS path, false AS cycle
  FROM nodes WHERE parent_id IS NULL
  UNION ALL
  SELECT n.id, n.parent_id, t.path || n.id, n.id = ANY(t.path)
  FROM nodes n JOIN tree t ON n.parent_id = t.id
  WHERE NOT t.cycle
)
SELECT * FROM tree WHERE NOT cycle;

Materialized CTE

Postgres: WITH cte AS MATERIALIZED (...) forces one execution and stores the result (AS NOT MATERIALIZED forces inlining). Use to prevent repeated evaluation of an expensive CTE, or to freeze a plan; but materialization blocks predicate pushdown, which can be slower.

WITH recent AS MATERIALIZED (
  SELECT * FROM orders WHERE created_at > now() - INTERVAL '7 days'
)
SELECT count(*) FROM recent;

Multiple CTEs

WITH a AS (...), b AS (SELECT ... FROM a) SELECT ... FROM b. Later CTEs can reference earlier ones. Improves stepwise transformation and keeps each stage testable.

WITH paid AS (
  SELECT * FROM orders WHERE status = 'paid'
), per_user AS (
  SELECT user_id, COUNT(*) AS n FROM paid GROUP BY user_id
)
SELECT * FROM per_user WHERE n > 3;

CTE for updates

WITH ... UPDATE/DELETE/INSERT ... SELECT. Useful for upserts and complex DML; Postgres supports data-modifying CTEs, which let you move rows between tables atomically. MySQL does not allow DML in a CTE body (only in the outer statement).

WITH moved AS (
  DELETE FROM staging
  WHERE processed = true
  RETURNING *
)
INSERT INTO archive SELECT * FROM moved;

Recursive CTE for sequences

Generate date series or numbers without a numbers table. Postgres also has generate_series; MySQL 8 has recursive CTEs only. Cap the recursion explicitly to avoid runaway generation.

WITH RECURSIVE seq(n) AS (
  SELECT 1
  UNION ALL
  SELECT n + 1 FROM seq WHERE n < 100
)
SELECT n FROM seq;

CTE scoping

A CTE is visible only within the single statement (including sub-statements for data-modifying CTEs). It is not persisted and cannot be reused across statements. Use views or materialized views for reuse; CTEs cannot be indexed separately.

WITH x AS (SELECT 1 AS n)
SELECT * FROM x;   -- ok

SELECT * FROM x;   -- error: relation "x" does not exist

Schema Design

Normal forms (1NF–BCNF)

1NF: atomic values, no repeating groups or arrays-in-a-column. 2NF: 1NF plus no partial dependency on part of a composite key. 3NF: 2NF plus no transitive dependency (non-key attribute depending on another non-key attribute). BCNF: every determinant is a candidate key—stricter than 3NF and removes the remaining anomalies. Most OLTP schemas target 3NF/BCNF; 4NF/5NF address multi-valued and join dependencies and rarely come up outside theory.

-- violates 3NF: zip -> city is a transitive dependency
CREATE TABLE users (
  id bigint PRIMARY KEY,
  zip  text,
  city text   -- depends on zip, not on id
);

-- 3NF: move the dependency to its own table
CREATE TABLE zips (zip text PRIMARY KEY, city text);
CREATE TABLE users (
  id  bigint PRIMARY KEY,
  zip text REFERENCES zips(zip)
);

Normalization vs denormalization

Normalize to remove redundancy and update anomalies (3NF/BCNF); denormalize deliberately for read performance (summary tables, materialized views, duplicated columns) and accept the write/consistency cost. Denormalize only after measuring—premature duplication creates drift you must maintain in code or triggers.

-- denormalized read model maintained on write
CREATE TABLE order_totals (
  order_id bigint PRIMARY KEY REFERENCES orders(id),
  total_cents bigint NOT NULL
);

Constraints: PK / FK / CHECK

PRIMARY KEY = unique + not null, one per table, and the target of foreign keys. FOREIGN KEY enforces referential integrity, with ON DELETE/ON UPDATE CASCADE, SET NULL, RESTRICT or NO ACTION. CHECK enforces a boolean predicate (avoid relying on it for cross-row rules). NOT NULL and UNIQUE handle presence and duplicates. Constraints are cheaper and safer than application-side checks; Postgres can add them NOT VALID and VALIDATE later to avoid a long lock.

CREATE TABLE accounts (
  id      bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  user_id bigint NOT NULL REFERENCES users(id) ON DELETE CASCADE,
  balance numeric(12,2) NOT NULL DEFAULT 0
          CHECK (balance >= 0),
  currency char(3) NOT NULL,
  UNIQUE (user_id, currency)
);

Cascading actions

ON DELETE CASCADE removes children; SET NULL requires a nullable FK column; RESTRICT (immediate) and NO ACTION (deferred until statement/transaction end) block deletes; SET DEFAULT restores the default. Cascades are convenient but can delete far more than intended—audit chains and prefer soft deletes for user-facing data. TRUNCATE cannot cascade to FK-referenced tables unless you use CASCADE.

ALTER TABLE comments
  ADD CONSTRAINT comments_post_fk
  FOREIGN KEY (post_id) REFERENCES posts(id)
  ON DELETE CASCADE
  ON UPDATE CASCADE;

-- Postgres: defer the check to commit time
ALTER TABLE comments
  ALTER CONSTRAINT comments_post_fk DEFERRABLE INITIALLY DEFERRED;

Views vs materialized views

A view is a stored query—no data, always current, re-planned on each access, and can be a security/abstraction layer. A materialized view stores the result: fast reads, stale until refreshed. Postgres: REFRESH MATERIALIZED VIEW [CONCURRENTLY] (concurrent refresh needs a unique index and takes longer). MySQL has no materialized views—use summary tables with scheduled jobs.

CREATE VIEW active_users AS
  SELECT id, email FROM users WHERE active;

CREATE MATERIALIZED VIEW daily_sales AS
  SELECT date_trunc('day', created_at) AS day, SUM(total) AS revenue
  FROM orders GROUP BY 1;

CREATE UNIQUE INDEX ON daily_sales (day);
REFRESH MATERIALIZED VIEW CONCURRENTLY daily_sales;

Performance

EXPLAIN / EXPLAIN ANALYZE

Show query plan. EXPLAIN ANALYZE actually executes and shows actual times/rows. Use to find seq scans, bad join types, sort spills. Compare estimated vs actual rows—large gaps mean stale or insufficient statistics. BUFFERS shows cache hits vs disk reads.

EXPLAIN (ANALYZE, BUFFERS)
SELECT * FROM orders WHERE user_id = 42;

-- look for: Seq Scan vs Index Scan, rows= estimates vs actual

Seq scan vs index scan

Seq scan reads the whole table; fine for small tables or when the query needs most rows. Index scan uses the index; better for selective predicates. The planner chooses on cost/statistics, not row count alone—correlation, random_page_cost and table width all matter. A surprising seq scan often means a missing index, a non-sargable predicate, or stale stats.

EXPLAIN ANALYZE
SELECT * FROM events WHERE user_id = 42;
-- Index Scan using idx_events_user on events (actual rows=12)

N+1 problem

Loop issuing one query per item. Fix with JOIN, IN, or batch loading. Common in ORMs; use eager loading / fetch joins. Watch for lazy relations serialized in a loop—the query count grows with page size.

-- N+1: 1 query for orders, then 1 per order
SELECT * FROM orders WHERE user_id = 42;
SELECT * FROM items WHERE order_id = ?;  -- x N

-- fixed: one join
SELECT o.id, i.sku, i.qty
FROM orders o JOIN items i ON i.order_id = o.id
WHERE o.user_id = 42;

Select only needed columns

Avoid SELECT *; it reduces I/O, memory and network transfer, and enables covering indexes. Especially important for wide tables and TOASTed/jsonb columns.

SELECT id, total FROM orders WHERE user_id = 42;

Batch operations

Use multi-row INSERT and batched updates to reduce round-trips. COPY (Postgres) for bulk load. Dropping/rebuilding indexes around a large load is sometimes faster, but it takes locks—measure. Batch sizes of a few hundred to a few thousand rows usually work best.

INSERT INTO events (user_id, kind)
VALUES (1, 'a'), (2, 'b'), (3, 'c');

COPY events (user_id, kind) FROM '/data/events.csv' CSV;

Query plan caching

Prepared statements cache plans; parameterized queries also prevent SQL injection and improve plan reuse. Postgres may switch to a generic plan after 5 executions, which is occasionally worse for skewed data—use plan_cache_mode or a hint-free rewrite. Avoid concatenating values into SQL.

PREPARE get_user (bigint) AS
  SELECT id, email FROM users WHERE id = $1;
EXECUTE get_user(42);

Statistics & ANALYZE

The optimizer relies on table statistics (row counts, distinct values, histograms, correlation). Run ANALYZE after large data changes; autovacuum/autoanalyze usually handles it but not after bulk loads. Stale stats → bad row estimates → nested-loop explosions or wrong join order.

ANALYZE orders;

SELECT attname, n_distinct, correlation
FROM pg_stats WHERE tablename = 'orders';

Connection pooling

Reuse DB connections (HikariCP, pgBouncer, PgCat). Avoid per-request connect/disconnect—TLS and auth are expensive. Tune pool size with the HikariCP/Postgres heuristic (cores * 2) + effective_spindles as a starting point, then measure; oversized pools increase contention and memory. Use transaction-mode pooling only if the app avoids session state.

-- pgBouncer (transaction pooling)
[pgbouncer]
pool_mode = transaction
max_client_conn = 1000
default_pool_size = 20

Lock contention

Long transactions hold locks; reduce transaction scope, avoid user interaction mid-transaction, and use appropriate isolation. Monitor pg_locks / pg_stat_activity or sys.dm_tran_locks. Idle-in-transaction sessions are a common culprit.

SELECT pid, state, wait_event_type, wait_event,
       now() - xact_start AS txn_age
FROM pg_stat_activity
WHERE xact_start IS NOT NULL
ORDER BY txn_age DESC;

Want this as flashcards? Study these 114 cards recall-first in the browser — flip, answer out loud, grade yourself.

Open the card deck