Notes
All notes

SQL: from SELECT to window functions

A product manager asks for a report: “revenue per plan, only for active customers, top 10, including customers with no orders.” You could write a thousand lines of application code, or one query. SQL exists so you write the what, not the how — and the database’s optimizer decides the fastest way to get it. That division of labor is the whole point of a declarative language, and it is why SQL has outlived nearly every technology from its era.

This post is a complete tour along the roadmap.sh/sql path. It deliberately spends time on theory — the relational model, relational algebra, normalization, three-valued logic, the cost model behind indexes and query plans, and the isolation theory behind transactions — because those ideas explain why the syntax works and when it will surprise you. The advanced half gives window functions a full treatment: what each function computes, how frames work, and where each one is the right tool. The companion quick reference is SQL crash course.

The relational model

A relational database represents all data as relations (tables). A relation is a set of tuples (rows) over a fixed set of named, typed attributes (columns). Two words measure a relation: its degree is the number of columns, and its cardinality is the number of rows.

Because a relation is a set, the model has no inherent row order and no duplicate rows. SQL relaxes both — tables are bags (multisets) that can contain duplicates and are returned in unspecified order unless you ORDER BY — which is why DISTINCT exists and why “the first row” is only meaningful with an explicit sort.

Keys are the model’s identity theory:

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  t/.style={draw, thick, rounded corners=3pt, minimum width=2.9cm, minimum height=0.62cm, font=\small\ttfamily, align=left},
  h/.style={t, fill=black!12, font=\small\bfseries\ttfamily},
  a/.style={->, thick}]
  \node[h] (u0) at (0,0) {users};
  \node[t] (u1) at (0,-0.7) {id (PK)};
  \node[t] (u2) at (0,-1.4) {name};
  \node[t] (u3) at (0,-2.1) {plan};
  \node[h] (o0) at (5,0) {orders};
  \node[t] (o1) at (5,-0.7) {id (PK)};
  \node[t] (o2) at (5,-1.4) {user\_id (FK)};
  \node[t] (o3) at (5,-2.1) {total};
  \draw[a] (u0) -- (o0) node[midway, above, font=\small] {1 : N};
\end{tikzpicture}

Relational algebra: the theory behind SQL

Every SQL query has a mathematical meaning as an expression in relational algebra, a small set of operators over relations:

Operator Symbol Meaning SQL
Selection \(\sigma_{p}\) keep rows satisfying predicate \(p\) WHERE
Projection \(\pi_{A}\) keep columns \(A\), remove others SELECT list
Rename \(\rho_{S}\) rename a relation AS
Join \(\bowtie_{p}\) combine rows from two relations on \(p\) JOIN ... ON
Union \(\cup\) set union UNION
Intersection \(\cap\) set intersection INTERSECT
Difference \(-\) set difference EXCEPT
Product \(\times\) cartesian product CROSS JOIN

A join is literally a selection over a cartesian product:

\[ R \bowtie_{p} S = \sigma_{p}(R \times S) \]

That definition is why a join is expensive in the abstract — the product has \(|R| \cdot |S|\) rows — and why the optimizer’s job is to avoid materializing it. This algebra is also the reason SQL is declarative: you write an algebra expression (the logical plan), and the optimizer rewrites it into an equivalent but cheaper physical plan (a WHERE pushed below a join, a hash join instead of a nested loop). Two queries that are algebraically equal can run at wildly different speeds.

The core SQL pipeline is one algebra expression:

\[ \text{result} = \pi_{\text{cols}}\big(\sigma_{\text{where}}(\text{FROM})\big) \ \text{grouped by } G \text{ and filtered by } H \]

Which is exactly the execution order we will see below.

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  b/.style={draw, thick, rounded corners=3pt, minimum height=0.64cm, font=\small\ttfamily},
  a/.style={->, thick}]
  \node[b, fill=blue!10, minimum width=1.8cm] (r) at (0,0.9) {relation};
  \node[b, fill=orange!16, minimum width=1.8cm] (s) at (0,-0.1) {$\sigma$ where};
  \node[b, fill=orange!16, minimum width=1.8cm] (j) at (0,-1.1) {$\bowtie$ join};
  \node[b, fill=green!16, minimum width=1.8cm] (p) at (0,-2.1) {$\pi$ select};
  \draw[a] (r) -- (s); \draw[a] (s) -- (j); \draw[a] (j) -- (p);
  \node[font=\rmfamily\small, text=black!60, anchor=west] at (1.2,-1.1) {each operator consumes and emits relations};
\end{tikzpicture}

SQL vs NoSQL. Relational databases give you a schema, ACID transactions, and joins — the right default when correctness and relationships matter (money, inventory). NoSQL stores trade guarantees for scale or a flexible shape (see Databases at Scale). Most applications, including large ones, are well served by a relational database.

QQuestionWhat is the difference between a primary key, a unique key, and a foreign key?
ASolution

A primary key uniquely identifies a row and is implicitly NOT NULL and UNIQUE; there is one per table. A unique key also enforces uniqueness but permits NULLs and you may have several. A foreign key references a key in another table and enforces referential integrity.

QQuestionWhat are super, candidate, primary, and foreign keys?
ASolution

A superkey is any set of columns that uniquely identifies a row. A candidate key is a minimal superkey (no column can be dropped). The primary key is the chosen candidate key, and a foreign key points at a candidate key in another relation.

Normalization and functional dependencies

Before writing queries you should understand how to design the schema, and that is a theory of dependencies.

A functional dependency \(X \to Y\) means: if two rows agree on the columns \(X\), they must agree on \(Y\). id -> email, plan says the id determines the rest of the row. Keys are the special case where \(X\) determines every attribute.

Bad schemas suffer three anomalies:

Normalization decomposes tables to remove redundancy, defined by normal forms:

Form Rule (informally)
1NF atomic values only; no repeating groups
2NF 1NF + no partial dependency on part of a composite key
3NF 2NF + no transitive dependency (non-key → non-key)
BCNF every determinant is a candidate key

The mantra is: every non-key attribute depends on “the key, the whole key, and nothing but the key.” Normalize to 3NF/BCNF for correctness, then denormalize deliberately (precompute a total, duplicate a name) only where read performance demands it and you can keep the copies consistent. Normalization is about eliminating update anomalies; denormalization is a measured performance trade, not a default.

QQuestionWhat is normalization, and why is it important?
ASolution

Normalization decomposes tables to remove redundancy, which prevents insertion, update, and deletion anomalies, and keeps each fact in one place. The normal forms (1NF, 2NF, 3NF, BCNF) formalize “every non-key attribute depends on the key, the whole key, and nothing but the key.”

QQuestionWhen would you denormalize?
ASolution

When a measured read bottleneck justifies it: duplicating a value or precomputing an aggregate removes a join or an aggregation at read time, at the cost of keeping copies consistent on write. Denormalize deliberately, not by default.

Basic syntax

SQL statements are declarative. The core shapes are SELECT (read), INSERT/UPDATE/DELETE (write), and CREATE/ALTER/DROP (define).

SELECT DISTINCT name, plan
FROM users
WHERE plan = 'pro' AND created_at >= '2026-01-01'
ORDER BY name ASC NULLS LAST
LIMIT 10 OFFSET 20;

Read the clauses as constraints on the result, not as steps. DISTINCT removes duplicate projected rows (the bag becomes a set). ORDER BY fixes an order; NULLS FIRST/LAST matters because NULL sorts unpredictably otherwise. LIMIT/OFFSET paginate but OFFSET scales linearly — we will fix that later.

QQuestionWhat is the difference between UNION and UNION ALL?
ASolution

Both stack the results of two SELECTs. UNION removes duplicate rows (which requires a sort or hash) and UNION ALL keeps every row and is therefore faster. Use UNION ALL unless you need deduplication.

QQuestionWhat are the SQL subsets DDL, DML, DCL, and TCL?
ASolution

DDL defines structure (CREATE, ALTER, DROP); DML changes data (SELECT, INSERT, UPDATE, DELETE); DCL controls access (GRANT, REVOKE); TCL manages transactions (BEGIN, COMMIT, ROLLBACK).

Execution order

The written order is not the execution order. The logical execution order is:

\[ \text{FROM} \to \text{WHERE} \to \text{GROUP BY} \to \text{HAVING} \to \text{SELECT} \to \text{DISTINCT} \to \text{ORDER BY} \to \text{LIMIT} \]

Each stage feeds the next a relation, which explains many rules:

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  b/.style={draw, thick, rounded corners=3pt, minimum height=0.6cm, font=\small\ttfamily},
  a/.style={->, thick}]
  \node[b, fill=blue!10, minimum width=1.15cm] (f) at (0,0) {FROM};
  \node[b, fill=blue!10, minimum width=1.3cm] (w) at (1.6,0) {WHERE};
  \node[b, fill=orange!16, minimum width=1.6cm] (g) at (3.4,0) {GROUP BY};
  \node[b, fill=orange!16, minimum width=1.4cm] (h) at (5.3,0) {HAVING};
  \node[b, fill=yellow!22, minimum width=1.7cm] (win) at (7.3,0) {WINDOW};
  \node[b, fill=green!16, minimum width=1.5cm] (s) at (9.3,0) {SELECT};
  \node[b, fill=green!16, minimum width=1.5cm] (o) at (11.1,0) {ORDER};
  \draw[a] (f) -- (w); \draw[a] (w) -- (g); \draw[a] (g) -- (h); \draw[a] (h) -- (win); \draw[a] (win) -- (s); \draw[a] (s) -- (o);
  \node[font=\rmfamily\small, text=black!60, anchor=north] at (5.3,-0.55) {rows shrink before aggregation; columns and window values are produced last};
\end{tikzpicture}

This is only the logical order. The optimizer may physically reorder everything as long as the result is identical — for example, pushing a WHERE predicate below a join, or evaluating a subquery once instead of per row.

QQuestionWhy can you not reference a SELECT alias in WHERE, but you can in ORDER BY?
ASolution

The logical execution order is FROM → WHERE → GROUP BY → HAVING → SELECT → ORDER BY. WHERE runs before the SELECT expressions are computed, so the alias does not exist yet; ORDER BY runs after, so it does.

QQuestionWhat is the difference between WHERE and HAVING?
ASolution

WHERE filters rows before grouping and cannot reference aggregates. HAVING filters groups after aggregation and can reference aggregate functions such as SUM(total) > 1000.

NULL and three-valued logic

NULL is not zero and not the empty string; it means unknown. SQL uses three-valued logic — every predicate is TRUE, FALSE, or UNKNOWN — and any comparison with NULL is UNKNOWN.

AND T F U
T T F U
F F F F
U U F U
OR T F U
T T T T
F T F U
U T U U

A WHERE clause keeps only rows where the predicate is TRUE; UNKNOWN rows are discarded. That is why WHERE x = NULL never matches (it is UNKNOWN, not true) and WHERE x <> NULL also never matches. Use IS NULL / IS NOT NULL, which are the only predicates that test for null directly.

SELECT COUNT(*)            AS total_rows,       -- counts every row
       COUNT(manager_id)   AS rows_with_mgr,    -- skips NULLs
       COUNT(*) - COUNT(manager_id) AS missing_mgr
FROM employees;

COALESCE(a, b, c) returns the first non-null; NULLIF(a, b) returns NULL if a = b, which is the standard guard against dividing by zero:

SELECT total / NULLIF(quantity, 0) AS unit_price FROM line_items;

Note that UNIQUE constraints, GROUP BY, and joins treat nulls specially: NULL = NULL is unknown, so two nulls do not “match” in a unique index or a join key. This is a common source of silent missing rows in reports.

QQuestionIs NULL the same as an empty string or zero?
ASolution

No. NULL means unknown, not any value; comparisons with it are UNKNOWN, so = NULL never matches and you must use IS NULL. '' and 0 are ordinary values.

QQuestionWhat does COALESCE do, and why is it useful in reports?
ASolution

It returns the first non-null argument. After a LEFT JOIN, a missing child row produces NULL, and COALESCE(SUM(o.total), 0) turns that into a 0 instead of a blank.

Data types

Choosing the right type is both a correctness decision and a performance one — narrow types make indexes smaller and comparisons faster.

Category Types Notes
Integers SMALLINT, INTEGER, BIGINT use BIGINT for ids that can grow
Exact decimal NUMERIC(p,s), DECIMAL money; never binary float
Approximate REAL, DOUBLE PRECISION measurements, not currency
Character TEXT, VARCHAR(n), CHAR(n) TEXT in Postgres has no penalty
Boolean BOOLEAN prefer over char flags
Temporal DATE, TIME, TIMESTAMP, TIMESTAMPTZ store UTC; use TIMESTAMPTZ
Semi-structured JSON, JSONB flexible attributes; index with GIN
Identity UUID, BIGSERIAL UUID for distributed ids
Composite ARRAY, ROW, range types powerful but non-portable

The float rule deserves emphasis: 0.1 + 0.2 is not exactly 0.3 in binary floating point, so summing prices as DOUBLE PRECISION accumulates error. NUMERIC stores exact decimal values.

QQuestionWhy should money never be stored as FLOAT?
ASolution

Binary floating point cannot represent most decimal fractions exactly, so summing prices accumulates rounding error. Use NUMERIC/DECIMAL, which store exact decimal values.

QQuestionWhat is the difference between CHAR and VARCHAR?
ASolution

CHAR is fixed length and padded with spaces; VARCHAR (or TEXT) stores variable-length strings. Use VARCHAR/TEXT unless every value truly has the same length.

Operators

Comparison (=, <>, <, <=, >), logical (AND, OR, NOT), pattern (LIKE, ILIKE, SIMILAR TO), regular expression (~), set (IN, BETWEEN, ANY, ALL), null (IS NULL), and string/array (||, @>). BETWEEN a AND b is inclusive on both ends and equivalent to a <= x AND x <= b.

QQuestionIs BETWEEN inclusive on both ends?
ASolution

Yes. x BETWEEN a AND b is exactly a <= x AND x <= b. The common bug is combining it with timestamps: BETWEEN '2026-01-01' AND '2026-01-31' misses most of the last day because the timestamp includes a time-of-day. Prefer >= start AND < next_day.

DDL: defining the schema

Data Definition Language creates and changes structure. Constraints are where integrity lives — push invariants into the schema so no application path can violate them.

CREATE TABLE users (
    id         BIGSERIAL PRIMARY KEY,
    email      TEXT NOT NULL UNIQUE,
    plan       TEXT NOT NULL DEFAULT 'free'
                 CHECK (plan IN ('free', 'pro', 'enterprise')),
    country    TEXT,
    created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE TABLE orders (
    id        BIGSERIAL PRIMARY KEY,
    user_id   BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    total     NUMERIC(10,2) NOT NULL CHECK (total >= 0),
    placed_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

The foreign key action defines what happens when the parent row is removed: CASCADE deletes children, RESTRICT/NO ACTION refuses, SET NULL nulls the reference. Choosing it is a statement about the domain.

ALTER TABLE users ADD COLUMN last_seen TIMESTAMPTZ;
ALTER TABLE users ADD CONSTRAINT valid_plan CHECK (plan <> '');
CREATE INDEX idx_orders_user_id ON orders(user_id);
DROP TABLE IF EXISTS old_table;

A generated column computes its value from others, keeping a derived value consistent by construction:

ALTER TABLE line_items
  ADD COLUMN total NUMERIC(12,2) GENERATED ALWAYS AS (quantity * unit_price) STORED;
QQuestionExplain the constraints NOT NULL, UNIQUE, CHECK, and DEFAULT.
ASolution

NOT NULL forbids missing values; UNIQUE forbids duplicates (allowing nulls); CHECK enforces a boolean condition; DEFAULT supplies a value when none is given. A primary key combines NOT NULL and UNIQUE.

QQuestionWhat is the difference between DELETE, TRUNCATE, and DROP?
ASolution

DELETE removes rows and is a DML statement: it supports WHERE, fires triggers, and is transactional. TRUNCATE removes every row quickly (like DDL), usually resets identity counters, and cannot target a subset. DROP removes the table (or object) itself, structure included.

DML: changing data

Data Manipulation Language reads and writes rows. Always scope writes with a WHERE clause; an unqualified UPDATE or DELETE rewrites the whole table.

INSERT INTO users (email, plan) VALUES ('a@example.com', 'pro');
UPDATE users SET plan = 'enterprise' WHERE email = 'a@example.com';
DELETE FROM orders WHERE placed_at < now() - INTERVAL '5 years';

An upsert inserts or updates on conflict — the atomic way to avoid a check-then-write race:

INSERT INTO users (email, plan) VALUES ('a@example.com', 'pro')
ON CONFLICT (email) DO UPDATE SET plan = EXCLUDED.plan;

RETURNING gives back the affected rows so you do not need a second SELECT:

INSERT INTO orders (user_id, total) VALUES (1, 49.99) RETURNING id, placed_at;

The SQL standard’s MERGE expresses “when matched update, when not matched insert” as one statement; the upsert above is the PostgreSQL shorthand.

QQuestionWhat is an upsert, and why is it better than check-then-insert?
ASolution

An upsert (INSERT ... ON CONFLICT DO UPDATE, or the standard MERGE) inserts or updates atomically. A check-then-insert has a race: two transactions can both see “no row” and both insert, causing a duplicate-key error or duplicate data.

Aggregate queries

Aggregation collapses many rows into one per group. It is the algebra’s grouping operator combined with a fold.

SELECT plan, COUNT(*) AS customers, AVG(created_at) AS avg_signup
FROM users
GROUP BY plan;

The aggregate functions are COUNT, SUM, AVG, MIN, MAX, plus statistical ones (STDDEV, VARIANCE, PERCENTILE_CONT). Two subtleties that cause real bugs: COUNT(*) counts rows while COUNT(column) skips NULLs, and the aggregate functions ignore NULL — AVG(x) divides by the count of non-null values, not the total rows.

WHERE filters rows before grouping; HAVING filters groups after:

SELECT user_id, SUM(total) AS revenue
FROM orders
WHERE placed_at >= '2026-01-01'      -- filters rows first
GROUP BY user_id
HAVING SUM(total) > 1000             -- filters groups after aggregation
ORDER BY revenue DESC;

Grouping sets, ROLLUP, and CUBE generalize GROUP BY to subtotals and grand totals in one pass:

SELECT COALESCE(plan, 'ALL') AS plan,
       COALESCE(country, 'ALL') AS country,
       SUM(total) AS revenue
FROM orders JOIN users ON users.id = orders.user_id
GROUP BY ROLLUP (plan, country);     -- detail, plan subtotals, grand total
\begin{tikzpicture}[font=\rmfamily, >=stealth,
  b/.style={draw, thick, rounded corners=3pt, minimum width=1.9cm, minimum height=0.62cm, font=\small\ttfamily},
  a/.style={->, thick}]
  \node[b, fill=blue!10] (r) at (0,0) {rows};
  \node[b, fill=orange!16] (g) at (2.6,0) {group by plan};
  \node[b, fill=green!16] (s) at (5.4,0) {one row per group};
  \draw[a] (r) -- (g); \draw[a] (g) -- (s);
  \node[font=\rmfamily\small, text=black!60, anchor=north] at (0,-0.55) {pro, pro, free, free, pro};
  \node[font=\rmfamily\small, text=black!60, anchor=north] at (2.7,-1.05) {pro $\to$ 3 rows, free $\to$ 2 rows};
\end{tikzpicture}
QQuestionWhat is the difference between COUNT(*) and COUNT(column)?
ASolution

COUNT(*) counts rows. COUNT(column) counts only rows where that column is not null, so the two differ whenever nulls are present. Aggregates such as AVG likewise ignore nulls and divide by the non-null count.

QQuestionHow do you get per-group subtotals and a grand total in one query?
ASolution

Use GROUP BY ROLLUP (...), or GROUPING SETS/CUBE. These add subtotal and total rows, marking the rolled-up columns as NULL, which you can label with COALESCE(plan, 'ALL').

JOIN queries

A join combines rows from two relations on a predicate; the definition is \(\sigma_p(R \times S)\) from the algebra section. A theta join uses any predicate; an equi-join uses equality; a natural join joins on all same-named columns (avoid it in production — it silently changes when columns are added). The type decides what happens to non-matching rows.

Join Keeps
INNER only matching rows in both
LEFT all left rows, NULL where right has none
RIGHT all right rows
FULL all rows from both sides
CROSS every pair (cartesian)
self a table joined to itself (hierarchies, pairs)

Revenue per user, including users with no orders — the classic left join:

SELECT u.name, COALESCE(SUM(o.total), 0) AS revenue
FROM users u
LEFT JOIN orders o ON o.user_id = u.id
GROUP BY u.id, u.name
ORDER BY revenue DESC;

COALESCE turns the NULL from “no matching rows” into 0. A self join answers hierarchy and pair questions:

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

Cardinality theory matters here. A join of a one-to-many relation multiplies rows: joining users to orders yields one row per order. If you then join another one-to-many relation (say payments), the two multiplications compound and your SUM double-counts. The rule is to aggregate each fact table on its own grain first, then join the aggregates.

EXISTS expresses a semijoin (keep left rows with a match) and NOT EXISTS an antijoin (keep left rows without one) — often more efficient and safer with nulls than IN/NOT IN:

SELECT u.name FROM users u
WHERE EXISTS (SELECT 1 FROM orders o WHERE o.user_id = u.id);
\begin{tikzpicture}[font=\rmfamily, >=stealth,
  c/.style={draw, thick, circle, minimum size=1.5cm, font=\small\ttfamily}]
  \node[c, fill=blue!12] (a) at (0,0) {users};
  \node[c, fill=orange!16] (b) at (1.5,0) {orders};
  \node[font=\small, anchor=north] at (0.75,-1.15) {inner = overlap};
  \node[font=\small, anchor=north] at (0.75,-1.5) {left = users + overlap};
\end{tikzpicture}
QQuestionExplain the JOIN types and when to use each.
ASolution

INNER keeps only matching rows; LEFT/RIGHT keep all rows from one side (with NULLs where there is no match); FULL keeps all rows from both; CROSS is the cartesian product. Use a LEFT JOIN with COALESCE when the related row may be absent, such as customers with no orders.

QQuestionHow do you find rows in one table that have no match in another?
ASolution

LEFT JOIN ... WHERE right.id IS NULL, or NOT EXISTS (the null-safe option), or EXCEPT. Avoid NOT IN when the subquery can return NULL, because it then returns no rows at all.

QQuestionHow do you find duplicate rows?
ASolution

Group by the identifying columns and keep groups larger than one: SELECT email, COUNT(*) FROM users GROUP BY email HAVING COUNT(*) > 1;.

Subqueries

A subquery is a query inside a query, and by the algebra it produces a relation that the outer query consumes. It can be scalar (one value), row, or table (many rows).

-- table subquery in FROM: aggregate once, then join
SELECT plan, AVG(revenue) AS avg_revenue
FROM (
    SELECT u.plan, o.user_id, SUM(o.total) AS revenue
    FROM users u JOIN orders o ON o.user_id = u.id
    GROUP BY u.plan, o.user_id
) per_user
GROUP BY plan;

A correlated subquery references a column of the outer row and is conceptually re-evaluated per row — the theory that makes it slow when the outer relation is large:

SELECT u.name,
       (SELECT COUNT(*) FROM orders o WHERE o.user_id = u.id) AS order_count
FROM users u;

The optimizer can sometimes decorrelate it into a join; when it cannot, rewrite it manually. EXISTS is preferable to IN for large subqueries because it can stop at the first match, and it is null-safe (NOT IN with a null in the list returns no rows at all).

QQuestionWhat is a correlated subquery, and why can it be slow?
ASolution

It references a column from the outer query and is conceptually evaluated once per outer row. That is why it is slow on large inputs; the optimizer may decorrelate it into a join, otherwise rewrite it as a join or a window function.

Advanced functions

Built-in functions shape data without application code:

SELECT
  UPPER(email)                              AS email_upper,
  LEFT(email, 3)                            AS prefix,
  COALESCE(country, 'unknown')              AS country,
  DATE_TRUNC('month', created_at)           AS month,
  CASE WHEN plan = 'free' THEN 0 ELSE 1 END AS is_paid,
  EXTRACT(EPOCH FROM now() - created_at) / 86400 AS age_days
FROM users;

DATE_TRUNC is the standard way to bucket a time series by day, week, or month.

QQuestionHow do you bucket a timestamp by month for a report?
ASolution

DATE_TRUNC('month', placed_at) in the GROUP BY (or SELECT), then group by that expression. For week or day granularity, change the unit.

Views

A view is a named stored query. It holds no data; it is expanded into the surrounding query when used, giving a reusable, permission-friendly interface.

CREATE VIEW active_revenue AS
SELECT u.plan, SUM(o.total) AS revenue
FROM users u JOIN orders o ON o.user_id = u.id
WHERE u.active
GROUP BY u.plan;

SELECT * FROM active_revenue WHERE revenue > 10000;

A simple view over one table can be updatable (writes pass through); a view over a join or aggregation generally is not. A materialized view stores the result physically and must be refreshed — the tool for expensive dashboards:

CREATE MATERIALIZED VIEW monthly_revenue AS
SELECT DATE_TRUNC('month', placed_at) AS month, SUM(total) AS revenue
FROM orders GROUP BY 1;

REFRESH MATERIALIZED VIEW CONCURRENTLY monthly_revenue;
QQuestionWhat is the difference between a view and a materialized view?
ASolution

A view is a stored query expanded at use: always current, no storage of its own. A materialized view stores the result physically and must be refreshed: fast reads for expensive queries, but potentially stale until the next refresh.

Indexes

An index is a sorted side structure (usually a B+ tree) that lets the database find rows without scanning the table. Its cost is theory worth knowing.

A B+ tree keeps keys sorted and balanced, so a point lookup, an insert, and a range scan are all \(O(\log n)\) in disk pages. For a million rows that is roughly 20 page reads instead of a million.

CREATE INDEX idx_orders_user_id ON orders(user_id);
CREATE UNIQUE INDEX idx_users_email ON users(email);
CREATE INDEX idx_orders_user_placed ON orders(user_id, placed_at DESC);

Selectivity is the fraction of rows a predicate keeps. An index only helps when the predicate is selective (keeps few rows); if it keeps 40% of the table, a sequential scan is cheaper, and the optimizer will ignore the index. A composite index follows the leftmost-prefix rule: (user_id, placed_at) serves predicates on user_id, or on user_id and placed_at, but not on placed_at alone. A covering index includes every column a query needs, so the table itself is never visited.

Index families:

Type Best for
B+ tree (default) equality, ranges, sorting, prefixes
Hash equality only
GIN arrays, JSONB, full-text
GiST geometry, ranges, nearest-neighbour
Partial indexing a filtered subset (WHERE active)
Expression CREATE INDEX ON users (LOWER(email))

Indexes are a write tax: every INSERT/UPDATE/DELETE maintains every index, and unused indexes waste space and slow writes. More indexes are not better.

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  b/.style={draw, thick, rounded corners=2pt, minimum width=1.5cm, minimum height=0.6cm, font=\small\ttfamily},
  a/.style={->, thick}]
  \node[b, fill=orange!20] (root) at (0,0) {index};
  \node[b, fill=blue!10] (leaf) at (0,-1) {leaf pages};
  \node[b, fill=green!14] (row) at (3,-1) {table row};
  \draw[a] (root) -- (leaf); \draw[a] (leaf) -- (row);
  \node[font=\rmfamily\small, text=black!60, anchor=north] at (1.2,-1.5) {index lookup jumps to the row, avoiding a full scan};
\end{tikzpicture}
QQuestionWhat is an index and why is it useful?
ASolution

A sorted side structure (usually a B+ tree) that lets the database find rows without scanning the table, turning a point lookup or range scan into roughly \(O(\log n)\) page reads. It speeds reads but costs storage and slows writes, since every change maintains it.

QQuestionWhat is the difference between a clustered and a non-clustered index?
ASolution

A clustered index defines the physical row order and there is at most one per table (InnoDB’s primary key is clustered). A non-clustered index is a separate structure whose leaves point at the rows, and a table can have many.

QQuestionWhen will the database ignore your index?
ASolution

When the predicate is not selective (it keeps a large fraction of rows), when the indexed column is wrapped in a function (WHERE DATE(created_at) = ... is not sargable), when types do not match, or when statistics are stale and the estimate is wrong.

Query planning and the cost model

When you send a query, the database runs a pipeline: parser → rewriter → planner/optimizer → executor. The planner is the interesting part. It enumerates logically equivalent plans, estimates each one’s cost from statistics (row counts, distinct-value counts, histograms), and picks the cheapest. This is cost-based optimization.

The cost estimate depends on physical join algorithms:

The planner’s cardinality estimates come from statistics, and bad estimates produce bad plans. Stale statistics are a common cause of a query that “suddenly” got slow. ANALYZE refreshes them.

\[ \text{cost} = \text{startup cost} + \text{run cost}, \qquad \text{chosen plan} = \arg\min_{\text{plan}} \text{cost}(\text{plan}) \]

EXPLAIN ANALYZE
SELECT u.name, SUM(o.total)
FROM users u JOIN orders o ON o.user_id = u.id
WHERE o.placed_at >= '2026-01-01'
GROUP BY u.name;

EXPLAIN shows the chosen plan and its estimated cost; EXPLAIN ANALYZE actually runs it and shows real time and row counts. Compare estimated vs actual rows: a large mismatch means the statistics, and therefore the plan, are wrong.

QQuestionWhat is a query plan, and what is EXPLAIN ANALYZE for?
ASolution

The plan is the physical strategy the cost-based optimizer chose: which indexes, join algorithms, and join order. EXPLAIN shows the plan with estimated costs and rows; EXPLAIN ANALYZE runs it and reports actual timings and row counts so you can compare estimates with reality.

QQuestionWhy might a query suddenly get slow?
ASolution

Commonly stale statistics producing a different plan, tables that grew past a threshold, a dropped or unused index, or lock contention. Re-running ANALYZE and re-reading the plan is the first move.

Transactions

A transaction groups statements so they succeed or fail as a unit, giving ACID:

BEGIN;
UPDATE accounts SET balance = balance - 100 WHERE id = 1;
UPDATE accounts SET balance = balance + 100 WHERE id = 2;
COMMIT;   -- or ROLLBACK to undo everything

Isolation theory: the anomalies

Isolation is graded because full isolation is slow. Each weaker level permits a specific anomaly, and knowing them is the theory behind the level choice.

Anomaly What happens
Dirty read you read another transaction’s uncommitted write
Non-repeatable read re-reading a row gives a different value
Phantom read re-running a query returns new rows
Lost update two writers overwrite each other’s change
Write skew two transactions each preserve an invariant, together breaking it
Level Dirty Non-repeatable Phantom
READ UNCOMMITTED yes yes yes
READ COMMITTED no yes yes
REPEATABLE READ no no yes*
SERIALIZABLE no no no
BEGIN ISOLATION LEVEL SERIALIZABLE;

PostgreSQL’s REPEATABLE READ prevents phantoms using MVCC snapshots; the standard permits them. Most engines default to READ COMMITTED; raise it only where correctness demands, because higher isolation serializes more work. MVCC (multi-version concurrency control) is how modern databases offer snapshots without readers blocking writers: each transaction sees a consistent version of the data.

Savepoints allow partial rollback inside a transaction:

BEGIN;
INSERT INTO orders (user_id, total) VALUES (1, 10);
SAVEPOINT before_line;
INSERT INTO order_lines (order_id, sku) VALUES (currval('orders_id_seq'), 'X');
ROLLBACK TO before_line;   -- undo only the last insert
COMMIT;
\begin{tikzpicture}[font=\rmfamily, >=stealth,
  b/.style={draw, thick, rounded corners=3pt, minimum height=0.6cm, font=\small\ttfamily},
  a/.style={->, thick}]
  \node[b, fill=green!16] (b) at (0,0) {BEGIN};
  \node[b, fill=blue!10] (s) at (2.4,0) {statements};
  \node[b, fill=green!16] (c) at (5,0) {COMMIT};
  \node[b, fill=red!12] (r) at (5,-1) {ROLLBACK};
  \draw[a] (b) -- (s); \draw[a] (s) -- (c); \draw[a] (s) -- (r);
\end{tikzpicture}
QQuestionExplain ACID.
ASolution

Atomicity — all statements commit or none do; Consistency — constraints and invariants hold before and after; Isolation — concurrent transactions do not corrupt each other; Durability — committed changes survive a crash.

QQuestionExplain the isolation levels and the anomalies each permits.
ASolution

READ UNCOMMITTED allows dirty reads; READ COMMITTED allows non-repeatable reads (and phantoms); REPEATABLE READ prevents non-repeatable reads but the standard still permits phantoms; SERIALIZABLE prevents all of these at the cost of concurrency. Lost updates and write skew are the anomalies people forget.

Data integrity and security

Integrity is enforced by constraints (primary keys, foreign keys, UNIQUE, CHECK, NOT NULL) and by transactions. Security is enforced by not handing the database to untrusted input.

The cardinal rule: never build SQL by string concatenation. This is the SQL injection bug:

# WRONG: the input becomes part of the query
cur.execute(f"SELECT * FROM users WHERE email = '{email}'")

Use parameterized queries, where the driver sends the SQL and the values separately, so a value can never be parsed as SQL:

# RIGHT: the value can never be parsed as SQL
cur.execute("SELECT * FROM users WHERE email = %s", (email,))

Then grant least privilege with roles instead of sharing a superuser, and use SECURITY DEFINER functions carefully:

CREATE ROLE reporting LOGIN PASSWORD '...';
GRANT SELECT ON active_revenue TO reporting;
REVOKE ALL ON users FROM PUBLIC;
QQuestionWhat is SQL injection, and how do you prevent it?
ASolution

It is untrusted input being interpreted as SQL because the query was built by string concatenation. Prevent it with parameterized queries (bind values separately) and least-privilege roles. Escaping quotes alone is fragile and not sufficient.

Stored procedures and functions

Stored routines run inside the database, reducing round trips and centralizing logic. A function returns a value and is used inside queries; a procedure performs actions and is called with CALL, and can control transactions.

CREATE FUNCTION monthly_revenue(p_month DATE) RETURNS NUMERIC AS $$
  SELECT COALESCE(SUM(total), 0) FROM orders
  WHERE placed_at >= p_month AND placed_at < p_month + INTERVAL '1 month';
$$ LANGUAGE sql STABLE;

SELECT monthly_revenue('2026-09-01');

Volatility tells the planner how to cache: IMMUTABLE (same input, same output, no database access), STABLE (consistent within a statement), VOLATILE (may change, default). Marking a function IMMUTABLE when it is not can make the planner fold it into an index and produce wrong results.

Triggers run code in response to row changes, useful for audit logs and enforcing rules that constraints cannot express. Keep them small and side-effect-light; logic hidden in triggers is hard to reason about.

QQuestionWhat is the difference between a stored procedure and a function?
ASolution

A function returns a value and can be used inside a query; a procedure performs actions, is invoked with CALL, and can manage transactions. Also mind volatility: marking a function IMMUTABLE when it reads the database can make the planner cache or index a wrong result.

Performance optimization

The method is always the same: measure, then index, then rewrite.

EXPLAIN ANALYZE
SELECT u.name, SUM(o.total)
FROM users u JOIN orders o ON o.user_id = u.id
WHERE o.placed_at >= '2026-01-01'
GROUP BY u.name;

Read the plan for: sequential scans on large tables (missing index), nested loops over many rows (bad join order or missing index), sorts that spill to disk, and estimates far from actuals (stale statistics — run ANALYZE).

Practical rules:

-- keyset pagination: stable and fast on large tables
SELECT id, total FROM orders
WHERE id > :last_seen_id
ORDER BY id
LIMIT 20;
QQuestionHow would you optimize a slow query?
ASolution

Start with EXPLAIN ANALYZE and look for sequential scans on large tables, nested loops over many rows, sorts spilling to disk, and estimates far from actuals. Then add or adjust indexes, make predicates sargable, fix N+1 access patterns, filter before joining, and refresh statistics with ANALYZE.

QQuestionHow do you find the second-highest salary?
ASolution

Three standard ways: SELECT MAX(salary) FROM emp WHERE salary < (SELECT MAX(salary) FROM emp);; ORDER BY salary DESC OFFSET 1 LIMIT 1;; or SELECT salary FROM (SELECT salary, DENSE_RANK() OVER (ORDER BY salary DESC) r FROM emp) t WHERE r = 2; The window version generalizes to the n-th highest.

QQuestionHow do you paginate without OFFSET?
ASolution

Keyset pagination: remember the last key and continue with WHERE id > :last ORDER BY id LIMIT 20. OFFSET scans and discards every skipped row, so it gets slower as the page number grows.

Common table expressions

A CTE (WITH) names an intermediate relation, turning nested subqueries into readable steps. Conceptually it is a let binding over a relation.

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

CTEs can be recursive, which is how SQL walks hierarchies and graphs. A recursive CTE has a base term and a recursive term combined by UNION ALL; the engine keeps applying the recursive term to newly produced rows until it yields none.

\[ R = R_{\text{base}} \cup R_{\text{step}}(R) \]

WITH RECURSIVE org AS (
    SELECT id, name, manager_id, 1 AS depth FROM employees WHERE manager_id IS NULL
    UNION ALL
    SELECT e.id, e.name, e.manager_id, o.depth + 1
    FROM employees e JOIN org o ON e.manager_id = o.id
)
SELECT * FROM org ORDER BY depth, name;

Every recursive CTE needs a termination condition, or it loops forever on a cycle. Guard with depth < n or the CYCLE clause.

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  n/.style={draw, thick, circle, minimum size=0.6cm, font=\small\bfseries, inner sep=0pt},
  a/.style={->, thick}]
  \node[n, fill=orange!28] (r) at (0,0) {CEO};
  \node[n, fill=blue!12] (a) at (-1.4,-0.9) {VP};
  \node[n, fill=blue!12] (b) at (1.4,-0.9) {VP};
  \node[n, fill=green!16] (c) at (-1.9,-1.8) {eng};
  \draw[a] (r) -- (a); \draw[a] (r) -- (b); \draw[a] (a) -- (c);
  \node[font=\rmfamily\small, text=black!60, anchor=north] at (0,-2.3) {each recursion step descends one level};
\end{tikzpicture}
QQuestionWhat is a CTE, and how does it differ from a subquery?
ASolution

A CTE is a named intermediate relation introduced with WITH, which improves readability and can be referenced several times. A subquery is inline. Whether a CTE is materialized once or inlined is engine-dependent, so check the plan for performance-critical queries.

QQuestionWhat is a recursive CTE used for?
ASolution

Walking hierarchies or graphs, such as an org chart or a bill of materials. It combines a base term with a recursive term via UNION ALL and iterates until no new rows appear. Always add a termination guard (a depth limit or the CYCLE clause) or a cyclic graph loops forever.

Window functions

Window functions are the most important advanced feature in SQL, and the one most often left unexplained. Here is the theory first.

A window function computes a value from a set of rows related to the current row and attaches it to the current row without collapsing the rows. Contrast with GROUP BY, which collapses each group into one row. A window is defined by three clauses:

\[ \underbrace{\text{PARTITION BY}}_{\text{which rows together}} \quad \underbrace{\text{ORDER BY}}_{\text{order within the window}} \quad \underbrace{\text{frame}}_{\text{which rows the function sees}} \]

Window functions run after WHERE, GROUP BY, and HAVING, but before ORDER BY. That is why they cannot appear in WHERE (you need a subquery or CTE to filter on a window result).

SELECT user_id, placed_at, total,
       SUM(total) OVER (PARTITION BY user_id ORDER BY placed_at) AS running_total
FROM orders;
\begin{tikzpicture}[font=\rmfamily, >=stealth,
  b/.style={draw, thick, minimum width=0.72cm, minimum height=0.55cm, font=\small\bfseries}]
  \foreach \v [count=\i from 0] in {10,20,15,30,25} { \node[b, fill=blue!8] at (\i*0.78,0) {\v}; }
  \draw[very thick, orange!75!black, rounded corners=2pt] (-0.38,-0.38) rectangle (1.16,0.38);
  \draw[very thick, green!55!black, rounded corners=2pt] (-0.38,-0.9) rectangle (3.5,-0.14);
  \node[font=\small, anchor=west] at (3.7,-0.5) {partition by user\_id};
  \node[font=\small, anchor=west] at (1.4,0.5) {frame: running total};
\end{tikzpicture}

The frames, precisely

A frame is specified with ROWS, RANGE, or GROUPS:

The bounds are UNBOUNDED PRECEDING, n PRECEDING, CURRENT ROW, n FOLLOWING, UNBOUNDED FOLLOWING, and you can EXCLUDE CURRENT ROW or EXCLUDE GROUP.

The default frame is the classic gotcha: with an ORDER BY, the default is RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW (a running total). Without an ORDER BY, the default is the entire partition. And because the default frame ends at the current row, LAST_VALUE returns the current row’s value, not the partition’s last — you need ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING for that.

Ranking functions

These order rows and assign positions.

ROW_NUMBER() assigns a unique, gap-free sequence per partition. The tool for “one row per group”.

SELECT id, user_id, total,
       ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY total DESC) AS rn
FROM orders;
-- filter rn = 1 (in a CTE) to get each user's largest order

RANK() assigns the same rank to ties and then skips: 1, 2, 2, 4.

DENSE_RANK() assigns the same rank to ties without skipping: 1, 2, 2, 3.

PERCENT_RANK() is the relative rank, (rank - 1) / (rows - 1), in [0, 1].

CUME_DIST() is the cumulative distribution: the fraction of rows with a value less than or equal to the current one.

NTILE(n) divides the partition into n roughly equal buckets and returns the bucket number — deciles, quartiles.

SELECT name, salary,
       RANK()       OVER w AS rank,
       DENSE_RANK() OVER w AS dense,
       NTILE(4)     OVER w AS quartile
FROM employees
WINDOW w AS (ORDER BY salary DESC);
Value ROW_NUMBER RANK DENSE_RANK
10 1 1 1
20 2 2 2
20 3 2 2
30 4 4 3

Value functions

These fetch a value from another row in the window.

LAG(col, n, default) returns the value n rows before the current one (default 1). LEAD looks forward. They are how you compute differences and month-over-month change without a self join.

SELECT month, revenue,
       LAG(revenue) OVER (ORDER BY month)             AS prev_month,
       revenue - LAG(revenue) OVER (ORDER BY month)   AS delta,
       ROUND(100.0 * (revenue - LAG(revenue) OVER (ORDER BY month))
             / NULLIF(LAG(revenue) OVER (ORDER BY month), 0), 1) AS pct_change
FROM monthly;

FIRST_VALUE(col), LAST_VALUE(col), and NTH_VALUE(col, n) return values from the frame’s first, last, or nth row. Remember the frame: FIRST_VALUE uses the frame start and usually behaves as expected, but LAST_VALUE with the default frame returns the current row, so specify ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING.

SELECT user_id, placed_at, total,
       FIRST_VALUE(total) OVER (PARTITION BY user_id ORDER BY placed_at
                                ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS first_order,
       LAST_VALUE(total)  OVER (PARTITION BY user_id ORDER BY placed_at
                                ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS last_order
FROM orders;

Aggregate windows

Any aggregate can be a window function by adding OVER. Instead of collapsing rows, it broadcasts the aggregate across the window.

SELECT user_id, total,
       SUM(total)   OVER (PARTITION BY user_id)                    AS user_total,
       AVG(total)   OVER (PARTITION BY user_id)                    AS user_avg,
       COUNT(*)     OVER (PARTITION BY user_id)                    AS user_orders,
       total / SUM(total) OVER (PARTITION BY user_id)              AS share_of_user,
       100.0 * total / SUM(total) OVER ()                          AS share_of_all
FROM orders;

SUM(...) OVER (ORDER BY ...) gives a running total; adding a bounded frame gives a moving average:

SELECT day, revenue,
       AVG(revenue) OVER (ORDER BY day ROWS BETWEEN 6 PRECEDING AND CURRENT ROW) AS ma_7
FROM daily;

OVER () with no partition is the whole result set — useful for shares of total.

Named windows

The WINDOW clause names a window definition reused by several functions, avoiding repetition and letting the planner reuse one sort.

SELECT user_id, placed_at, total,
       ROW_NUMBER() OVER w AS rn,
       SUM(total)   OVER w AS running,
       AVG(total)   OVER w AS running_avg
FROM orders
WINDOW w AS (PARTITION BY user_id ORDER BY placed_at);

What each window function is for

Function Computes Typical use
ROW_NUMBER unique sequence dedupe, top-1 per group
RANK rank with gaps leaderboards
DENSE_RANK rank without gaps “nth distinct value”
PERCENT_RANK relative rank 0–1 percentile position
CUME_DIST cumulative distribution “what fraction are below”
NTILE(n) bucket number quartiles, deciles
LAG / LEAD previous / next value deltas, MoM change
FIRST_VALUE first in frame baseline value
LAST_VALUE last in frame latest value (mind the frame)
NTH_VALUE nth in frame top-3 comparisons
SUM/AVG/COUNT/MIN/MAX OVER aggregate over frame running totals, moving averages, shares

Execution and performance

The engine typically sorts each partition by the window’s ORDER BY, then streams rows through the frame. Sharing a WINDOW definition across several functions lets it sort once instead of per function. Windows are cheaper than a self join or a correlated subquery for the same result, but they still require a sort; an index on (partition columns, order columns) can supply that order and avoid it.

QQuestionWhat is the difference between an aggregate function and a window function?
ASolution

An aggregate collapses a group into one row (SUM with GROUP BY). A window function computes over a set of related rows but keeps every row, attaching the result to each. That is why windows cannot appear in WHERE: they are computed after it.

QQuestionWhat is the difference between ROW_NUMBER, RANK, and DENSE_RANK?
ASolution

On ties, ROW_NUMBER still assigns a unique number (1, 2, 3, 4), RANK gives tied rows the same rank and then skips (1, 2, 2, 4), and DENSE_RANK gives the same rank without skipping (1, 2, 2, 3).

QQuestionWhat is the frame clause, and which default surprises people?
ASolution

The frame is the slice of the ordered partition a window function sees, written with ROWS, RANGE, or GROUPS between bounds. With an ORDER BY, the default frame ends at the current row, so LAST_VALUE returns the current row, not the partition’s last. Specify ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING for the true last value.

QQuestionHow do you get the top N rows per group?
ASolution

Number rows within each group and filter: WITH t AS (SELECT *, ROW_NUMBER() OVER (PARTITION BY grp ORDER BY metric DESC) rn FROM data) SELECT * FROM t WHERE rn <= N;

QQuestionHow do you remove duplicates while keeping the most recent row?
ASolution

Rank by recency and delete the rest: WITH t AS (SELECT id, ROW_NUMBER() OVER (PARTITION BY key ORDER BY updated_at DESC) rn FROM data) DELETE FROM data WHERE id IN (SELECT id FROM t WHERE rn > 1);

Pivot and unpivot

Reshaping between long (one row per measurement) and wide (one column per category) is common in reporting. Databases differ in syntax, but the portable technique is conditional aggregation:

SELECT DATE_TRUNC('month', placed_at) AS month,
       SUM(CASE WHEN plan = 'free' THEN total ELSE 0 END) AS free_rev,
       SUM(CASE WHEN plan = 'pro'  THEN total ELSE 0 END) AS pro_rev
FROM orders o JOIN users u ON u.id = o.user_id
GROUP BY 1 ORDER BY 1;

FILTER (WHERE ...) is the standard shorthand for the same thing and reads more clearly:

SELECT DATE_TRUNC('month', placed_at) AS month,
       SUM(total) FILTER (WHERE plan = 'free') AS free_rev,
       SUM(total) FILTER (WHERE plan = 'pro')  AS pro_rev
FROM orders o JOIN users u ON u.id = o.user_id
GROUP BY 1 ORDER BY 1;
QQuestionHow do you pivot rows to columns without a PIVOT function?
ASolution

Use conditional aggregation: SELECT month, SUM(CASE WHEN plan = 'free' THEN total END) AS free_rev, SUM(CASE WHEN plan = 'pro' THEN total END) AS pro_rev FROM ... GROUP BY month; The FILTER (WHERE plan = 'free') form is the standard shorthand.

Dynamic SQL

Dynamic SQL builds and executes a query string at runtime — necessary for flexible reporting UIs (choose columns, filters, sort order). Do it with parameter binding for values and an allow-list for identifiers (table and column names cannot be bound as parameters):

# value is bound; column comes from a trusted allow-list, never user text
allowed = {"total", "placed_at", "user_id"}
col = sort_col if sort_col in allowed else "placed_at"
cur.execute(f"SELECT id, total FROM orders ORDER BY {col} LIMIT %s", (limit,))

The danger is identifier injection: a bind parameter cannot substitute a column name, so any dynamic identifier must be validated against a fixed set.

QQuestionWhat is dynamic SQL, and what is the risk?
ASolution

Building a query string at runtime, needed for flexible reporting UIs. The risk is injection: bind values as parameters, and validate identifiers (table and column names) against an allow-list, because parameters cannot stand in for identifiers.

Putting it together

The opening request, in one query:

SELECT u.plan,
       COUNT(DISTINCT u.id)            AS customers,
       COALESCE(SUM(o.total), 0)       AS revenue
FROM users u
LEFT JOIN orders o ON o.user_id = u.id
WHERE u.active
GROUP BY u.plan
ORDER BY revenue DESC
LIMIT 10;

And the same data shaped per customer with a running total and a rank, using windows:

WITH order_totals AS (
    SELECT u.id, u.plan, u.name,
           SUM(o.total)                                  AS revenue,
           ROW_NUMBER() OVER (PARTITION BY u.plan ORDER BY SUM(o.total) DESC) AS rn
    FROM users u LEFT JOIN orders o ON o.user_id = u.id
    GROUP BY u.id, u.plan, u.name
)
SELECT plan, name, revenue
FROM order_totals
WHERE rn <= 3
ORDER BY plan, rn;

That one statement uses a CTE, a left join, aggregation, a window function, and filtering on a window result — the whole advanced toolkit.

Pitfalls

QQuestionSelf-check

Why can’t a window function appear in WHERE? What is the difference between ROW_NUMBER, RANK, and DENSE_RANK, and why does LAST_VALUE often surprise people?

ASolution

Windows are computed after WHERE, GROUP BY, and HAVING, so their values do not exist when WHERE runs; filter them in a CTE or outer query. ROW_NUMBER is unique and gap-free; RANK ties share a rank and then skip; DENSE_RANK ties share a rank without skipping. LAST_VALUE uses the frame, and the default frame ends at the current row, so it returns the current row unless you specify ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING.

Next: try the SQL crash course as a quick refresher, or Databases at Scale for indexing and sharding at production scale.