Skip to content
Tech Interview Prep
Technical interview guide

SQL Fundamentals

SELECT, WHERE, and JOIN: retrieving and combining rows from relational tables.

Minutes to read
3
Practice MCQs
25
Interview Q&A
25
Edition
v4
Editorial status
Reviewed

Scope: SQL principles with PostgreSQL 18 examples; vendor-specific behavior must be verified.

Interview Q&A

Treat each question like a live interview question: answer out loud first (structure, assumptions, tradeoffs), then open the model answer to spot gaps and rehearse a tighter follow-up.

Curated: · Written: · Reviewed:

25 questions

Q&A-1

Walk through SQL's logical processing order and explain why it matters in practice.

Answer

The order. FROM and its joins → WHERE → GROUP BY → HAVING → window functions → SELECT → DISTINCT → ORDER BY → LIMIT/OFFSET. It is a semantic model, not an execution plan: the planner reorders physical work freely as long as the result matches. What the model buys you is a prediction of which names and which values exist at each step, and therefore which errors you will hit.

stepwhat it can reference
FROM / JOINbase tables, join predicates
WHEREbase columns only: no select alias, no aggregate, no window function
GROUP BYbase columns; output aliases allowed in PostgreSQL and MySQL
HAVINGaggregates; output aliases only in MySQL
window functionsaggregates and base columns, but not other window functions
SELECTaggregates, window functions; aliases are born here
ORDER BYoutput aliases in PostgreSQL and MySQL
LIMIT / OFFSETa row count, nothing else

A trace. PostgreSQL 16:

SQL
SELECT region,
       count(*)                             AS orders,
       rank() OVER (ORDER BY count(*) DESC) AS rnk
FROM sales
WHERE status = 'paid'
GROUP BY region
HAVING count(*) > 100
ORDER BY orders DESC
LIMIT 3;
  1. FROM sales: the row set exists.
  2. WHERE status = 'paid': unpaid rows dropped. count(*) is not defined yet, so WHERE count(*) > 100 is an error, not a slow query.
  3. GROUP BY region: one row per region; count(*) becomes computable.
  4. HAVING count(*) > 100: regions with 100 or fewer paid orders dropped.
  5. rank() OVER (...): computed over the surviving groups.
  6. SELECT: projects region, orders, rnk.
  7. ORDER BY orders DESC: the alias resolves because SELECT already ran.
  8. LIMIT 3: three rows.

Failure modes this predicts.

  • Alias in WHERE. SELECT price * 1.2 AS price_with_tax FROM items WHERE price_with_tax > 100 fails with ERROR: column "price_with_tax" does not exist in PostgreSQL and ERROR 1054 (42S22): Unknown column 'price_with_tax' in 'where clause' in MySQL. Repeat the expression or wrap the query in a subquery.
  • Alias in HAVING. PostgreSQL rejects HAVING orders > 100 with ERROR: column "orders" does not exist; MySQL accepts it as an extension. Portable SQL repeats the aggregate.
  • Filtering a window function. rnk cannot appear in WHERE or HAVING: window functions run after HAVING. You need a CTE or subquery, which is the usual reason a "simple" ranking query grows a wrapper.
  • SELECT DISTINCT with an ORDER BY expression outside the select list. PostgreSQL: ERROR: for SELECT DISTINCT, ORDER BY expressions must appear in select list. DISTINCT runs before ORDER BY, so the sort key must survive the deduplication.
  • LIMIT without ORDER BY. LIMIT runs last, so it returns an arbitrary ten rows from a set whose order the engine never promised. It is stable in practice on a small, unchanging table and not stable in general.

Optimisation. A predicate that does not involve an aggregate belongs in WHERE, not HAVING: WHERE filters before grouping, so fewer rows reach the aggregate. In HAVING it is semantically after grouping, and while some planners push it down, you should not depend on that. The same reasoning explains why WHERE on a partitioned or indexed column is where the planner can actually use the index: by the time HAVING runs, the grouping work is already paid for.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-2

Explain NULL semantics in SQL and the bugs three-valued logic causes.

Answer

NULL means unknown, not empty and not zero. SQL evaluates predicates in three-valued logic (TRUE, FALSE, UNKNOWN) and WHERE keeps only rows evaluating to TRUE. Any comparison involving NULL yields UNKNOWN, so x = NULL and x <> NULL both match nothing. The correct tests are IS NULL and IS NOT NULL, or IS DISTINCT FROM when you want NULL to behave like a comparable value, which is invaluable for change detection.

The expensive bug is NOT IN against a nullable subquery. x NOT IN (1, 2, NULL) is UNKNOWN whenever x is not 1 or 2, because the engine cannot rule out that the NULL equals x, so the query returns zero rows silently, with no error. NOT EXISTS has no such behaviour and is the anti-join I reach for by default.

Aggregates ignore NULLs, which is why COUNT(*) and COUNT(col) differ by exactly the NULL count: a useful one-line audit. SUM over zero rows returns NULL rather than 0, so report queries wrap it in COALESCE. Outer joins manufacture NULLs for unmatched rows, so a predicate on the right table placed in WHERE rather than ON quietly converts a LEFT JOIN into an inner join.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-21

Explain the difference between UNION, INTERSECT, and EXCEPT with a practical use.

Answer

Set operations combine result sets vertically rather than sideways. All of them require the inputs to have the same number of columns with compatible types, positionally: column names come from the first query and are not matched by name, which is a real source of bugs when someone reorders one branch's select list.

UNION returns rows in either input with duplicates removed. UNION ALL is the same without deduplication, and it is what I default to: deduplication costs a sort or hash, and if duplicates are impossible you are paying for nothing. I use plain UNION only when duplicates are both possible and unwanted.

INTERSECT returns rows present in both inputs: useful for 'customers who bought in both January and June'. EXCEPT returns rows in the first input but not the second: 'users who signed up but never logged in'. Both deduplicate by default, with ALL variants that do not.

The practical case I reach for these in most is reconciliation between two systems: A EXCEPT B gives what is missing from B, B EXCEPT A gives what is unexpected in B, and running both gives a complete diff in two queries.

That said, INTERSECT and EXCEPT are frequently expressible as joins or EXISTS/NOT EXISTS, which are usually more flexible because they let you return columns from both sides rather than only the compared projection. I use the set operators when the symmetry makes the intent clearer, and joins when I need more than the compared columns.

Curated: · Written: · Reviewed:

Difficulty: Easy
Q&A-14

Explain the difference between DISTINCT, GROUP BY, and DISTINCT ON.

Answer

The 60-second answer

All three reduce row count, but they answer different questions. DISTINCT asks which whole rows are unique? GROUP BY asks what are the aggregates per key? DISTINCT ON asks which single row per key, chosen by this ordering? The deciding question is what you need out the other side: a value computed across the group (GROUP BY), a whole row picked by a rule (DISTINCT ON), or just the set of distinct tuples (DISTINCT).

Mechanism

DISTINCT and GROUP BY over the same column list are the same operation to the planner: it either builds a HashAggregate or sorts and runs a Unique node. That is why they are interchangeable for pure deduplication and usually produce the same plan.

DISTINCT ON cannot use a hash aggregate: it needs rows physically ordered so that the first row per key is the one to keep, so PostgreSQL implements it as Unique over a Sort. That single fact explains its two rules: the ORDER BY is mandatory, and its leading expressions must match the DISTINCT ON expressions, or you get SELECT DISTINCT ON expressions must match initial ORDER BY expressions.

DISTINCTGROUP BYDISTINCT ON
Collapsesduplicate whole rowsrows per grouping keyrows per key, keeping one
Select listonly the deduped columnsgrouping cols + aggregatesany columns
ORDER BYoptionaloptionalrequired, leading with the ON exprs
PlanHashAggregate or Sort+UniqueHashAggregate or GroupAggregateSort+Unique
Standard SQLyesyesno: PostgreSQL extension

Worked trace

orders
 id | customer_id | created_at | total
----+-------------+------------+------
  1 |          10 | 2024-01-05 |    40
  2 |          10 | 2024-02-11 |    15
  3 |          11 | 2024-01-20 |    90
  4 |          11 | 2024-03-01 |    25
  5 |          12 | 2024-03-02 |    60

SELECT DISTINCT customer_id FROM orders; → 10, 11, 12.

SELECT customer_id, count(*) FROM orders GROUP BY customer_id; → 10|2, 11|2, 12|1.

SELECT DISTINCT ON (customer_id) * FROM orders ORDER BY customer_id, created_at DESC; → rows 2, 4, 5: the most recent order per customer, every column intact. The window equivalent, ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY created_at DESC) filtered to rn = 1 in an outer query, returns the same three rows.

Failure modes

  • DISTINCT and GROUP BY need an equality operator on every column involved. SELECT DISTINCT payload FROM events where payload is json fails with could not identify an equality operator for type json; jsonb works because it defines equality.
  • SELECT DISTINCT customer_id FROM orders ORDER BY created_at fails with for SELECT DISTINCT, ORDER BY expressions must appear in select list. DISTINCT ON has no such restriction, which is exactly why it exists.
  • DISTINCT ON without a deterministic tiebreaker picks an arbitrary row among ties. Add a unique column (ORDER BY customer_id, created_at DESC, id DESC) when the choice must be reproducible.
  • GROUP BY on a table's primary key lets you select that table's other columns (functional dependency, PostgreSQL 9.1+). DISTINCT has no equivalent rule.

Choosing

Reach for GROUP BY when you want a count, sum or max alongside the key: it states the intent. Use DISTINCT only for genuine set semantics, and treat an unexpected one as a signal that a join is fanning out. Use DISTINCT ON when you are committed to PostgreSQL and want the shortest query for "latest row per key"; use the window form when you need portability or the rank for something else in the same query.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-9

Explain the difference between GROUP BY aggregation and a window function.

Answer

The 60-second answer. GROUP BY changes the shape of the result: N input rows become one row per distinct key, and every selected expression must be an aggregate or a grouping key, because the individual rows no longer exist. A window function leaves the row count untouched: every input row comes out, with an extra column computed over a set of related rows. The test that decides it: do you still need per-row detail in the output? Yes → window. No → GROUP BY.

Worked example. Four orders, two regions, checked on PostgreSQL 16:

SQL
CREATE TABLE orders (order_id int, region text, amount int);
INSERT INTO orders VALUES (1,'east',100),(2,'east',300),(3,'west',200),(4,'west',50);

SELECT region, SUM(amount) AS region_total
FROM orders GROUP BY region;
-- east | 400
-- west | 250          <- 4 rows in, 2 rows out

SELECT order_id, region, amount,
       SUM(amount)  OVER (PARTITION BY region)                    AS region_total,
       RANK()       OVER (PARTITION BY region ORDER BY amount DESC) AS rnk,
       ROUND(100.0 * amount / SUM(amount) OVER (PARTITION BY region), 1) AS pct
FROM orders;
-- 2 | east | 300 | 400 | 1 | 75.0
-- 1 | east | 100 | 400 | 2 | 25.0
-- 3 | west | 200 | 250 | 1 | 80.0
-- 4 | west |  50 | 250 | 2 | 20.0   <- 4 rows in, 4 rows out

Row order is shown for readability; add an outer ORDER BY to guarantee it. The pct column is the thing GROUP BY cannot produce in one pass: each row's share of its region's total, with the row still present.

Mechanism. PARTITION BY is the window analogue of GROUP BY, it decides which rows share a window, but it partitions without collapsing. ORDER BY inside OVER establishes sequence, which is what ranking and running totals need. A frame clause narrows the window further; with an ORDER BY and no explicit frame, the default is RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW, which is why SUM(amount) OVER (PARTITION BY region ORDER BY amount DESC) is a running total.

Evaluation order is FROM → WHERE → GROUP BY → HAVING → window functions → SELECT list → DISTINCT → ORDER BY → LIMIT. Window functions run after grouping, so they can consume aggregates (SUM(SUM(amount)) OVER (PARTITION BY region)), and they run before ORDER BY, so an ORDER BY may reference them.

Failure modes.

  • Filtering on a window result in WHERE fails outright: window functions are not allowed in WHERE. Wrap the query in a subquery or CTE and filter outside. That is the shape of every top-N-per-group query:
SQL
SELECT * FROM (
  SELECT order_id, region, amount,
         ROW_NUMBER() OVER (PARTITION BY region ORDER BY amount DESC) AS rn
  FROM orders
) t WHERE rn = 1;
  • The default RANGE frame includes peers. Two rows tied on amount get the same running total, which jumps by both amounts at once. Use ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW when you need strict row-by-row accumulation.
  • Window functions cannot be nested; a window over a window needs another subquery level.
  • NULLs form their own partition under PARTITION BY, and PostgreSQL orders NULLs last for ASC and first for DESC, so a ROW_NUMBER() ... ORDER BY amount DESC can hand rank 1 to a NULL amount.
  • PostgreSQL rejects SELECT DISTINCT alongside a window function in the select list.

Cost. GROUP BY can run as a HashAggregate, holding one entry per distinct group. A window with PARTITION BY plus ORDER BY needs the partition sorted, so EXPLAIN typically shows a Sort feeding WindowAgg: n log n over the whole input, not just the groups. If you only need the aggregate, GROUP BY is the cheaper plan; reach for the window when the per-row detail has to survive.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-10

How do you choose between INNER, LEFT, and FULL joins when assembling a report?

Answer

I choose from which rows must survive when there is no match. INNER JOIN when a row is only meaningful with its counterpart: order lines with their order. LEFT JOIN when the left side is the subject of the report and related data is optional: every customer, with their most recent order if they have one. FULL JOIN when both sides are independently meaningful, which in practice is mostly reconciliation work: comparing two systems and surfacing what exists in one but not the other.

The LEFT JOIN trap is where you filter. A predicate on the right table in WHERE runs after the join and discards the NULL-extended rows, converting the LEFT JOIN into an inner join without any error. If the condition describes what counts as a match, it goes in ON; if it describes which final rows you want, WHERE is correct, but then be sure you actually want inner-join behaviour.

The deliberate use of that interaction is the anti-join: LEFT JOIN then WHERE right.id IS NULL returns exactly the left rows with no match, which is how you find customers with no orders. NOT EXISTS expresses the same thing more directly and I usually prefer it.

I also check fan-out whenever I add a join. If the right side has multiple matches per left row, the left row is duplicated and any subsequent aggregate is inflated, which is a correctness question, not a performance one.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-12

What is a self join, and what is a classic scenario where you must join a table to itself?

Answer

A self join is not a distinct SQL keyword; it is an ordinary join where the same table appears on both sides of the join operator. Because the engine cannot distinguish columns from identical table names, you must assign distinct table aliases to each instance.

Classic Scenario: Hierarchical / Adjacency-List Relationships

The standard case is resolving a recursive or unary relationship within a single entity, such as an employee reporting hierarchy where each employee references another employee's primary key via manager_id.

SQL
-- employees: id (int PK), name (text), manager_id (int FK -> employees.id)
SELECT
    e.name AS employee_name,
    COALESCE(m.name, 'Top Level') AS manager_name
FROM employees AS e
LEFT JOIN employees AS m
    ON e.manager_id = m.id;

I use a LEFT JOIN here instead of an INNER JOIN so the root of the hierarchy (the CEO or top-level node with manager_id IS NULL) remains in the result set rather than being dropped.

Second Scenario: Successive Row Comparison Without Window Functions

Another frequent scenario is comparing adjacent events or finding non-overlapping intervals, such as finding logins from the same user that occurred within 5 minutes of each other:

SQL
SELECT
    curr.user_id,
    curr.login_time AS initial_login,
    nxt.login_time AS subsequent_login
FROM user_logins AS curr
JOIN user_logins AS nxt
    ON  curr.user_id = nxt.user_id
    AND curr.login_time < nxt.login_time
    AND nxt.login_time <= curr.login_time + INTERVAL '5 minutes';

Mechanism, Trade-offs, and Traps

  1. Predicate Directionality: When comparing pairs of rows in the same table (e.g., finding duplicate emails or overlapping bookings), joining on a.id != b.id returns every pair twice ((A, B) and (B, A)). Using a strict inequality like a.id < b.id breaks symmetry, eliminating duplicate mirror rows and preventing self-matching (a.id = b.id).
  2. Quadratic Cardinality ($O(N^2)$ Fan-out): If join predicates are loose or non-selective (e.g., joining an event log back onto itself on user_id without narrow time ranges), the query forces an $O(N^2)$ Cartesian explosion per partition, blowing up memory usage in hash joins or disk spooling in merge/nested loop joins.
  3. Arbitrary Depth Limits: A single self join resolves exactly one step in an adjacency list (direct manager). If you need multi-level paths (employee to CEO across arbitrary depths), self joins do not scale; you must use a recursive CTE (WITH RECURSIVE).

Curated: · Written: · Reviewed:

Difficulty: Easy
Q&A-3

A report's revenue total doubled after a new join was added. How do you diagnose it?

Answer

My first hypothesis is join fan-out. Adding a join to a table with more than one matching row per parent duplicates the parent row, and any parent-side value summed afterwards is counted once per duplicate.

I confirm it cheaply: run the query without the aggregate and compare the row count before and after the new join, or group by the parent key and look for counts above one. That distinguishes fan-out from an actual data change in a few seconds.

The fix depends on intent. If I only need to test for a related row, EXISTS replaces the join and cannot duplicate anything. If I need a value from the child, I aggregate the child in a subquery or CTE to one row per parent key and join to that. If I genuinely need child detail alongside parent totals, I compute the parent aggregate separately from the detail rather than summing across a fanned-out result, or use a window function so the aggregate is evaluated over a defined partition instead of the duplicated set.

What I avoid is patching it with SELECT DISTINCT. That masks the symptom, is wrong the moment two legitimately distinct child rows share every projected value, and leaves the next engineer with no idea why the DISTINCT is there.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-8

Write and explain a query that finds duplicate rows by a business key.

Answer

Core answer

SQL
SELECT email, COUNT(*) AS n
FROM users
GROUP BY email
HAVING COUNT(*) > 1;

GROUP BY collapses each key to one row; HAVING then filters those groups. It must be HAVING, not WHERE, WHERE runs before grouping and cannot see COUNT(*). Checked on PostgreSQL 16 and MySQL 8.0.

Getting the offending rows, not just the keys

SQL
SELECT id, email, created_at, rn
FROM (
  SELECT id, email, created_at,
         ROW_NUMBER() OVER (PARTITION BY LOWER(TRIM(email))
                            ORDER BY created_at, id) AS rn
  FROM users
) t
WHERE rn > 1;

Trace over four rows:

idemailcreated_atpartition keyrn
1a@x.com2024-01-01a@x.com1
2a@x.com2024-02-01a@x.com2
3b@x.com2024-01-15b@x.com1
4A@x.com2024-03-01a@x.com3

The result is ids 2 and 4. Row 4 only lands in the same partition because the partition key is normalised: grouping on raw email would have missed it. That is the usual reason a duplicate hunt returns nothing while duplicates are visibly present.

ORDER BY created_at, id needs the id tiebreaker. Without it, two rows sharing a timestamp get an arbitrary rank, and the row you keep changes between runs.

Two traps before you delete

NULLs. GROUP BY treats all NULL emails as one group, so they show up as duplicates, but a plain UNIQUE (email) in PostgreSQL and MySQL permits unlimited NULLs. Decide whether NULL is a valid key before you build a constraint that cannot enforce what your query just reported.

Normalised keys need a matching index. UNIQUE (email) does not stop A@x.com and a@x.com coexisting; you need the expression:

SQL
CREATE UNIQUE INDEX CONCURRENTLY users_email_lower_key
  ON users (LOWER(TRIM(email)));

CONCURRENTLY cannot run inside a transaction block, so it cannot share the transaction that does the delete. Run the delete, commit, then build the index, and check pg_index.indisvalid afterwards, because a failed concurrent build leaves an invalid index behind.

Removal

SQL
DELETE FROM users u
USING (
  SELECT id, ROW_NUMBER() OVER (PARTITION BY LOWER(TRIM(email))
                                ORDER BY created_at, id) AS rn
  FROM users
) d
WHERE u.id = d.id AND d.rn > 1;

MySQL 8.0 rejects this shape with error 1093 (you cannot select from the table you are deleting from); wrap the derived table in one more SELECT ... FROM (...) x.

Before running it: SELECT COUNT(*) the rn > 1 set, repoint foreign keys to the surviving id, and do the delete in a transaction. If children reference the doomed rows, the delete either fails on the FK or orphans them.

Cost

With a btree index on the key, PostgreSQL can use GroupAggregate over an index scan: no sort, no hash table. Without one it picks HashAggregate, whose memory scales with distinct keys, not rows; work_mem defaults to 4 MB, so a table with millions of distinct emails spills to disk. The window form always sorts or hashes by the partition key, so it is the more expensive of the two: use the GROUP BY form to find keys, the window form only to fetch rows.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-7

When would you use a CTE, a subquery, or a temporary table?

Answer

Two questions decide it: how many times the intermediate result is read, and whether the engine materializes it. Everything else is style.

  • Subquery: read once, small, and the surrounding statement stays readable. Scalar lookups, IN, EXISTS. Past about two nesting levels it stops paying.
  • CTE: read more than once in the same statement, or the name is what makes the query legible, or the logic is recursive. A WITH chain reads as named steps instead of an inside-out pyramid.
  • Temp table: read across several statements, or you want to index it, gather statistics on it, or restart a batch job at a stage boundary.

The materialization fence is the real decision. On PostgreSQL 11 and earlier every CTE was materialized: an optimisation fence. PostgreSQL 12 changed the default: a non-recursive CTE referenced exactly once is inlined into the outer query, and MATERIALIZED / NOT MATERIALIZED force either behaviour. Recursive CTEs are always materialized; a CTE referenced more than once is materialized by default, and NOT MATERIALIZED will inline it into each reference, duplicating the work. SQL Server goes the other way: a CTE is expanded inline, so referencing it twice runs the underlying query twice. MySQL 8.0 materializes CTEs into an internal temporary table. The same WITH clause can therefore be a pushdown barrier on one engine and free on another; check EXPLAIN rather than assuming.

Concretely, on PostgreSQL 12+, this is a case where the CTE costs you:

SQL
-- referenced once: PG 12+ inlines this, so the predicate reaches the index
WITH recent AS (SELECT * FROM orders WHERE created_at > now() - interval '1 day')
SELECT * FROM recent WHERE customer_id = 42;

On PostgreSQL 11 the same query materializes all of yesterday's orders and then filters. On 12+ the customer_id predicate is pushed into the scan. If you want the old behaviour deliberately, an expensive step evaluated once, write WITH recent AS MATERIALIZED (...).

Recursion is the case where a CTE is not a style choice. This walks an org chart:

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

With employees = (1,NULL), (2,1), (3,1), (4,2): iteration 1 emits (1,1); iteration 2 joins on manager_id = 1 and emits (2,2), (3,2); iteration 3 emits (4,3); iteration 4 produces nothing, the working table empties, and the recursion stops. Output: 1/1, 2/2, 3/2, 4/3. A subquery cannot express this, and a temp table would need a loop around it.

The failure mode that bites most often is NOT IN against a nullable subquery. With parent(id) = (1),(2) and child(parent_id) = (1),(NULL):

SQL
SELECT id FROM parent WHERE id NOT IN (SELECT parent_id FROM child);  -- 0 rows
SELECT id FROM parent WHERE NOT EXISTS
  (SELECT 1 FROM child WHERE child.parent_id = parent.id);           -- 2 rows

The first returns nothing: the subquery yields {1, NULL}, so the predicate becomes id <> 1 AND id <> NULL, which is NULL for every row and never true. NOT EXISTS is null-safe. That is a subquery bug rather than a CTE one, but it is why NOT EXISTS is the default in review.

Temp tables are a real object with real cost: writes, cleanup, and on PostgreSQL a per-session pg_temp_N schema you can scope with ON COMMIT DROP. On SQL Server a #temp table lands in tempdb and gets statistics and indexes, which is exactly why it wins when the intermediate result is large and queried repeatedly: the optimiser has something to work with. Do not create one to tidy up a single statement.

read onceread N timesrecursiveindexablesurvives statement
subqueryyesnononono
CTEyes (inlined on PG 12+)yes (materialized by default)yesnono
temp tableyesyesvia loopyesyes

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-25

Write and explain a recursive CTE that walks an employee-to-manager reporting chain, covering the anchor member, recursive member, termination, cycle protection, and when a recursive CTE beats a fixed-depth self join.

Answer

A recursive CTE has two parts: an anchor member that seeds the result, and a recursive member that references the CTE by name and is evaluated repeatedly until it returns no rows. For an employee-to-manager chain, the anchor is the root (manager_id IS NULL), and the recursive member joins employees to the current frontier on manager_id = org.id.

sql CREATE TABLE employees ( id int PRIMARY KEY, name text NOT NULL, manager_id int REFERENCES employees(id) );

WITH RECURSIVE org AS ( -- anchor: top of the tree SELECT id, name, manager_id, 1 AS depth, ARRAY[id] AS path FROM employees WHERE manager_id IS NULL UNION ALL -- recursive: direct reports of the current frontier SELECT e.id, e.name, e.manager_id, o.depth + 1, o.path || e.id FROM employees e JOIN org o ON e.manager_id = o.id WHERE NOT e.id = ANY(o.path) -- cycle guard AND o.depth < 10 -- depth backstop ) SELECT id, name, depth, path FROM org ORDER BY path;

Termination is implicit: the recursive term returns zero rows when no employee has manager_id equal to any id in the last iteration's frontier. A cycle breaks that. If A manages B and B manages A, the frontier never empties. The path array excludes already-visited ids; PostgreSQL 14+ also has a CYCLE id SET is_cycle USING path clause that does this natively. A depth limit is a backstop, not a fix.

Use UNION ALL, not UNION. UNION deduplicates the whole row, which is expensive and only accidentally stops cycles when the row is identical; with a depth column it will not.

When is a recursive CTE the right tool? Arbitrary or unknown depth. If depth is known and small, exactly three levels of management, three self joins are simpler and the planner can choose join orders. A recursive CTE is iterative: each iteration scans the working table, so it can be slower than a set-based join for fixed depth. It also cannot use aggregates, GROUP BY, ORDER BY, or LIMIT in the recursive term, and the recursive reference must appear exactly once in the FROM clause.

AspectRecursive CTEFixed-depth self join
Deptharbitraryknown, fixed
Syntaxanchor + recursive memberN joins
Terminationempty recursive termimplicit
Cycle riskyes, needs guardno (unless data cycles)
Planneriterative, materializedset-based joins
Use whentree, graph, bill of materialsexactly N levels

Failure modes: a missing index on manager_id turns each iteration into a sequential scan. For a 10,000-row employee table, a recursive CTE from the CEO visits each employee once: 10,000 index lookups. Without the index, each of the ~10 iterations scans 10,000 rows: 100,000 row reads. A cycle without a guard fills temp space until the query is killed; you see it in pg_stat_activity as an active recursive CTE with growing temp files. A 5-level self join silently misses the sixth level if the tree is deeper.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-22

What is the difference between a natural key and a surrogate key?

Answer

A natural key is a column that already exists in the data and means something to the business: an ISBN, an ISO 3166 country code, an email address. A surrogate key is a value the system invents purely to identify the row: a sequence integer, a UUID. The framing that decides most designs is that identity and uniqueness are two separate jobs, and you can give each its own constraint instead of forcing one column to do both.

My default: surrogate primary key, plus a unique constraint on the natural key.

SQL
-- PostgreSQL 16
CREATE TABLE customer (
  id         bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  email      text NOT NULL,
  created_at timestamptz NOT NULL DEFAULT now(),
  CONSTRAINT customer_email_key UNIQUE (email)
);

CREATE TABLE order_line (
  id          bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  customer_id bigint NOT NULL REFERENCES customer(id),
  sku         text NOT NULL
);

Now a customer changes their email. That is one UPDATE touching one row and one index. If email were the primary key, the same update has to cascade into every child table that references it. In Postgres, ON UPDATE CASCADE rewrites each referencing row and its index entries; without it you get ERROR: update or delete on table "customer" violates foreign key constraint "order_line_customer_id_fkey" on table "order_line" (SQLSTATE 23503). With five child tables at a few million rows each, that is a multi-table write transaction holding row locks the whole way.

Width is the second cost. Postgres btree entries are the key plus an 8-byte index tuple header, rounded up to 8-byte alignment:

keybytesentry100M-row index
bigint identity816~1.6 GB
uuid1624~2.4 GB
text email, ~30 chars3040~4.0 GB

Those are at 100% fill; real indexes sit lower after churn, so treat them as a floor. Every secondary index that carries the key pays the same multiplier, and every foreign key column in every child table is as wide as the parent key.

Sequence vs UUID, once you have picked surrogate:

  • bigint identity: 8 bytes, monotonic, so inserts land at the right edge of the B-tree. Good locality. Downsides: it leaks row volume and is trivially guessable in a URL (/orders/1043), and in Postgres nextval is non-transactional, so rolled-back transactions leave gaps.
  • UUIDv4: 16 bytes, client-generatable with no round trip, unguessable. Random values scatter inserts across the whole B-tree, causing page splits and more WAL.
  • UUIDv7 / ULID: 16 bytes with a time-ordered prefix, so you get client generation and near-sequential insert locality. This is what I would pick for a distributed or offline-capable writer.

Failure modes worth naming:

  • Surrogate PK with no unique constraint on the natural key. "The id is the primary key" is not a uniqueness rule; you get two customer rows with the same email and no error. Detect it with a duplicate query before adding the constraint.
  • Natural key on a mutable value: email, username, phone number. The cascade is the symptom; the cause is that you keyed on something the business edits.
  • Natural key that is only almost unique. ISBNs get reissued, country codes change (CS to RS), tax IDs get recycled. A surrogate absorbs that; a natural PK turns it into a migration.

Composite natural keys are still right in junction tables: (student_id, course_id) in an enrollment table is the identity, and a surrogate there just adds a column and an index nobody queries.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-6

Which integrity rules belong in the database rather than the application, and why?

Answer

Anything that must be true of the data regardless of who wrote it belongs in the schema. The database is the one component every application, migration script, background job, admin console and manual psql session passes through. Application validation is a usability feature, it produces good error messages, but it is not a guarantee, because the next writer may not run that code.

Concretely: NOT NULL for required values; PRIMARY KEY for row identity; UNIQUE for real-world uniqueness such as an email or an external reference; FOREIGN KEY for relationships, with the ON DELETE action chosen deliberately rather than defaulted; and CHECK for row-level invariants such as a non-negative quantity or an end date at or after a start date.

The foreign-key action is a genuine design decision. RESTRICT refuses to orphan rows and is the safe default. CASCADE suits genuine composition, where the child has no meaning without its parent: order lines with an order. SET NULL suits optional references, such as a task whose assignee leaves.

My caveats: constraints that require checking many rows, or cross-row invariants, often cannot be expressed declaratively and need a different mechanism. A unique partial index, an exclusion constraint, or serialisable isolation. And adding a constraint to a large live table needs a validated-then-enforced migration so it does not hold a long lock. Neither caveat is a reason to move the guarantee into the application.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-17

Explain how you would model a many-to-many relationship and query it.

Answer

A many-to-many relationship needs a third table, a junction or join table, holding one row per association. For students and courses, an enrolments table with student_id and course_id, each a foreign key to its parent.

The primary key should be the composite of both columns. That enforces the rule that a student cannot enrol in the same course twice, which is exactly the integrity constraint the design needs, and it gives an index supporting lookups by student. I add a second index on course_id so the reverse lookup, everyone enrolled in a course, is also indexed, because a composite key only serves queries leading with its first column.

A surrogate id on the junction table is worth adding only when something else must reference an individual association, or when the ORM requires it. Otherwise it adds a column and an index without adding a guarantee, and if you add it, keep the unique constraint on the pair, or you have just permitted the duplicates the composite key was preventing.

The junction table is also the natural home for attributes of the relationship itself: enrolled_at, grade, role. That is a positive reason to model it explicitly rather than hiding it behind an ORM abstraction.

Querying is a two-hop join: students to enrolments to courses. Two things to watch: filtering on the far side of a LEFT JOIN belongs in ON if you want to preserve students with no enrolments, and any aggregate over the joined result is subject to fan-out, since one student produces one row per enrolment.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-19

Explain the trade-offs of storing JSON in a relational database.

Answer

The 60-second version. "Storing JSON" is two different decisions: a text column holding a payload, or a native type (json/jsonb in PostgreSQL). Only the native type is worth discussing for querying: text is a blob with no operators. I reach for jsonb when the shape is genuinely variable or genuinely opaque: per-integration settings, third-party payloads kept verbatim for replay, sparse optional attributes where a hundred mostly-null columns would be worse. I don't use it for fields that are queried, filtered, joined, aggregated or constrained: those become columns.

What jsonb actually is. It parses on write into a binary container: keys deduplicated, order not preserved, whitespace dropped. json keeps the exact text. That difference decides audit and replay cases, if you must reproduce the bytes a vendor sent, use json or text, not jsonb.

What you give up.

  • No NOT NULL, no type enforcement, no foreign key into a document. You can add CHECK constraints on extracted paths, but that is manual and only covers the paths you thought of.
  • No per-key statistics. The planner has no histogram for payload->>'status', so selectivity estimates for JSON predicates fall back to defaults and plans go wrong on large tables.
  • An update rewrites the whole document (and its TOAST entry), so a hot row with a large document is a write-amplification problem.
  • Schema drift is invisible: nothing fails until a consumer reads a shape it did not expect.

Indexing is a deliberate choice, not automatic. GIN with the default jsonb_ops supports ?, ?|, ?& and @>; GIN with jsonb_path_ops supports only @> but the index is smaller and faster for containment. An expression B-tree on one extracted path is the other option when a single field is queried like a column.

SQL
-- PostgreSQL 16
CREATE TABLE events (
  id      bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  payload jsonb NOT NULL,
  status  text GENERATED ALWAYS AS (payload->>'status') STORED,
  CONSTRAINT status_known CHECK (status IN ('queued','sent','failed'))
);

CREATE INDEX events_status_idx  ON events (status);
CREATE INDEX events_payload_gin ON events USING gin (payload jsonb_path_ops);

The generated column is the promotion path: the document stays the source of truth, but status is a real column with a real index and a real constraint, enforced on write.

The trap, traced. WHERE payload->>'status' = 'failed' will not use events_status_idx: that index is on status, not on the expression. You need WHERE status = 'failed', or a separate expression index ON events ((payload->>'status')). Same data, different plan.

jsonjsonbcolumns
key order / duplicate keyspreservednot preserved, dedupedn/a
indexableexpression onlyGIN, expression B-treeB-tree and others
constraintsnoneCHECK on extracted pathsfull
planner statisticsnonenone per keyhistogram
update costwhole valuewhole valueper column

The failure mode I look for in review is a jsonb column whose keys are in fact fixed and known. That is a table someone did not want to write a migration for, and it costs more later: every consumer re-implements validation, and you cannot add a foreign key or a NOT NULL without a backfill. When not to use it: anything you join on, anything with a stable schema, anything where a wrong value must be rejected at write time.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-16

How would you design soft deletion, and what does it cost?

Answer

Soft deletion marks a row as deleted rather than removing it: typically a nullable deleted_at timestamp, which is more useful than a boolean because it records when and sorts naturally. The motivation is recoverability, audit and preserving referential targets for historical records.

The cost is that every query must now exclude deleted rows, and the failure mode is silent: one forgotten WHERE deleted_at IS NULL leaks deleted data into a listing or a count. I do not rely on discipline for that. I expose the filter once: a view over the table that applies it, or row-level security, or a repository layer where the default query is filtered and including deleted rows requires an explicit opt-in.

Unique constraints are the second problem. A plain unique constraint on email blocks re-registering an address that belongs to a deleted account. The fix is a partial unique index that applies only where deleted_at IS NULL, so uniqueness holds among live rows only.

Third, foreign keys do not understand soft deletion. The database will happily let a live child reference a soft-deleted parent, because the row is still there. That has to be an application rule, and it needs deliberate handling: cascade the soft delete, block it, or accept it explicitly.

Then there is growth (deleted rows sit in the table and in every index forever, degrading scans) and privacy, because a deletion request under GDPR or similar means actual erasure, not a flag. So I usually pair soft deletion with a retention job that hard-deletes or anonymises after a defined window.

When the real requirement is audit history rather than undo, an append-only history table or event log is often the better design, because it records what changed and by whom rather than only that a row is gone.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-23

What are transactions in SQL, and what does ACID guarantee in a relational database?

Answer

A transaction is a logical unit of work that groups one or more SQL statements so they succeed or fail as a single operation, demarcated by BEGIN (or START TRANSACTION) and COMMIT or ROLLBACK.

ACID defines the four guarantees an engine must provide over that boundary:

  • Atomicity (All-or-nothing): If any statement fails, or the client aborts or crashes mid-flight, all intermediate modifications are rolled back. There is no half-written state. PostgreSQL implements this using Write-Ahead Logging (WAL) and Multi-Version Concurrency Control (MVCC) row metadata (tracking xmin and xmax transaction IDs), marking aborted transactions as uncommitted in the commit log (pg_xact).
  • Consistency (Valid state transitions): The database moves from one valid state to another, satisfying all defined schema invariants (such as NOT NULL, CHECK, UNIQUE, and foreign key constraints) before and after the transaction commits. If a statement violates CHECK (balance >= 0), the statement (or the entire transaction block) fails.
  • Isolation (Concurrency safety): Concurrent transactions cannot see each other's uncommitted intermediate work, preventing anomalies. ANSI SQL defines four isolation levels based on three read phenomena:
LevelDirty ReadNon-repeatable ReadPhantom Read
Read UncommittedPrevented in PGPrevented in PGPrevented in PG
Read Committed (PG default)NoYesYes
Repeatable ReadNoNoPrevented in PG
SerializableNoNoNo

In PostgreSQL, Read Uncommitted is treated as Read Committed. At Read Committed, every statement takes a fresh snapshot of committed data, meaning two identical SELECTs within one transaction can return different data if another transaction commits in between. Repeatable Read fixes this by taking a single snapshot at the start of the first statement, while Serializable detects read/write conflicts (SSI) and aborts with a serialization failure (40001) if non-serializable interleaving occurs.

  • Durability (Survivability): Once COMMIT completes, changes persist across power loss or crashes. The engine achieves this by flushing WAL buffers to disk (via an fsync system call) before reporting success to the client.

Worked Trace: Ledger Transfer

SQL
BEGIN;

UPDATE accounts
SET balance = balance - 100
WHERE id = 1 AND balance >= 100;
-- If rowcount is 0, client issues ROLLBACK because funds are insufficient

UPDATE accounts
SET balance = balance + 100
WHERE id = 2;

COMMIT;

If the server loses power right after updating account 2, recovery replays the WAL: if COMMIT was written, both accounts reflect the change; if not, neither does (Atomicity + Durability).

Practical Trade-Offs and Failure Modes

  1. Lock Contention and Deadlocks: Row-level locks taken by UPDATE or SELECT FOR UPDATE are held until transaction termination. Long-running transactions (such as wrapping third-party HTTP calls inside a DB transaction) exhaust connection pools and trigger deadlocks.
  2. Serialization Failures: Operating at SERIALIZABLE or REPEATABLE READ requires application-level retry loops for code 40001 (serialization_failure).
  3. Premature Durability Tuning: Disabling synchronous_commit gives higher write throughput by returning before fsync, but risks losing the last few milliseconds of committed transactions during a hard crash.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-24

Explain SQL transaction isolation levels, the anomalies each one permits, and how you would choose a level for a given workload.

Answer

Assume PostgreSQL 18 and its default, READ COMMITTED. The SQL standard defines four isolation levels by which of three read anomalies they forbid:

LevelDirty readNon-repeatable readPhantom read
READ UNCOMMITTEDallowedallowedallowed
READ COMMITTEDpreventedallowedallowed
REPEATABLE READpreventedpreventedallowed by the standard
SERIALIZABLEpreventedpreventedprevented

PostgreSQL never exposes uncommitted rows, so READ UNCOMMITTED behaves as READ COMMITTED, and its REPEATABLE READ also prevents phantoms: it is stronger than the standard's minimum. The mechanism is MVCC: READ COMMITTED takes a fresh snapshot per statement, so a re-read inside the same transaction can see another transaction's commit; REPEATABLE READ pins one snapshot for the whole transaction, so every read is consistent and new rows cannot appear. SERIALIZABLE adds serializable snapshot isolation, which tracks read/write dependencies and aborts a transaction with SQLSTATE 40001 when the result would not match any serial order.

The anomalies are not academic. Under READ COMMITTED a read-modify-write loses updates: two sessions read balance = 100, both write 90, one is silently lost. Fix it with SELECT ... FOR UPDATE or a single atomic UPDATE accounts SET balance = balance - 10 WHERE id = 1. Under REPEATABLE READ you still get write skew, because snapshot isolation only detects conflicting writes to the same row. Trace it on on_call(doctor, on_call) with the invariant "at least one doctor on call": T1 and T2 each run SELECT count(*) FROM on_call WHERE on_call and both see 2, each sets its own row to false, both commit. Different rows, no write conflict, invariant broken. Only SERIALIZABLE catches that.

So the choice follows the invariant, not the table. READ COMMITTED for ordinary OLTP: maximum concurrency, no retries, provided every read-modify-write is a single statement or takes a row lock. REPEATABLE READ for a multi-statement report that must see one consistent snapshot, such as a 30-second revenue rollup where each statement has to agree with the last. SERIALIZABLE when the invariant spans rows the transaction does not lock: bookings, inventory, ledgers. The cost is aborts, not blocking: expect a few percent of contended SERIALIZABLE transactions to fail and need a retry:

python for attempt in range(5): try: with conn.transaction(isolation_level="SERIALIZABLE"): book_seat(seat_id, user_id) break except SerializationFailure: # SQLSTATE 40001 time.sleep(0.01 * 2 ** attempt)

Two costs to name out loud: retries must be idempotent, and long REPEATABLE READ or SERIALIZABLE transactions hold back the xmin horizon, so vacuum cannot reclaim dead rows. Keep them short.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-4

How do you prevent SQL injection, and why is escaping insufficient?

Answer

Injection happens when user data is concatenated into query text, so the parser cannot tell data from syntax. The fix is parameterized statements: the driver sends the SQL text and the values over separate channels, and the value is bound after parsing. A parameter can therefore never be reinterpreted as syntax, whatever it contains. It usually improves plan reuse as a bonus.

Escaping is weaker because it is a filtering approach: it depends on applying exactly the right transformation, for the right context, at every single call site, forever. It has been defeated repeatedly by character-set edge cases, nested contexts and one developer forgetting once. Parameterization removes the class of bug instead of policing it.

Some things genuinely cannot be parameterized: table and column names, and ORDER BY direction, are identifiers rather than values. For those I use a strict allowlist mapping user input to a fixed set of known-safe identifiers, never string interpolation.

I treat the remaining measures as defence in depth, not the fix: least-privilege database roles so a successful injection reaches little, and stored-procedure or ORM layers that make parameterization the default path. An ORM is not automatic protection: its raw-SQL escape hatch concatenates just as dangerously as anything else.

Curated: · Written: · Reviewed:

Difficulty: Easy
Q&A-15

What is sargability, and how does it affect whether an index is used?

Answer

The 90-second answer. A predicate is sargable when the engine can turn it into a range over an index's sorted keys, a seek, instead of evaluating it once per row. The rule that decides it: the indexed column must appear bare on one side of the comparison, and the other side must be computable without reading the row. created_at >= '2026-01-01' is sargable; YEAR(created_at) = 2026 is not, because the engine would have to compute YEAR() for every row before it could compare anything. Sargability is necessary for a seek but not sufficient: the planner still weighs the seek against a sequential scan by cost.

Why the rule is what it is. A B-tree is stored in key order. To seek, the engine needs a lower and upper bound it can compute once, before touching the table: created_at >= X AND created_at < Y hands it both. Any expression containing the column destroys that: the bound depends on the row, so there is nothing to seek to. A function of a constant is fine (created_at >= now() - interval '7 days' is evaluated once and stays sargable); a function of the column is not.

predicateseek?why
created_at >= '2026-01-01' AND created_at < '2027-01-01'yesboth bounds computed once
YEAR(created_at) = 2026nobound depends on each row
email LIKE 'ann%'yes*prefix gives a range
email LIKE '%ann%'nono prefix to seek to
lower(email) = :vnofunction of the column
amount * 12 > 1000noarithmetic on the column
status IN ('a','b')yesone seek per value
status <> 'a'nonot a range; scan or bitmap
col IS NULLyesnulls are stored in the B-tree

*In Postgres, only if the index is C-collation or built with text_pattern_ops; a default B-tree under en_US.UTF-8 cannot serve LIKE 'ann%'.

Rewrites. YEAR(created_at) = 2026 becomes created_at >= '2026-01-01' AND created_at < '2027-01-01': same rows, seek restored. amount * 12 > 1000 becomes amount > 1000.0 / 12. Watch the literal: in Postgres 1000 / 12 with two integer literals truncates to 83, harmless for an integer column but wrong for a numeric one, so write 1000.0 / 12 or the decimal. lower(email) = :v has three fixes: store a normalised column, build an expression index on lower(email) (the query must then match the expression exactly), or use a case-insensitive collation.

Implicit conversion is engine-specific. In SQL Server, WHERE varchar_col = 42 converts the column to int, int has higher precedence, so the index on that column is dead; the same happens when a client binds a parameter as text against an int column. Oracle converts the column too. Postgres resolves it the other way, casting the literal to text, and the seek survives. Same-looking SQL, opposite plans: check the engine's type-precedence rules rather than assuming.

Composite indexes. A B-tree on (a, b, c) can be seeked on a prefix. A range on a stops the seek from using b and c for bounds: the index is still scanned in order and can filter, but the seek narrows to a's range only. Equality-first ordering is a heuristic, not a law; verify with the plan.

Sargable but still scanned. Cost decides. Rough model: a 10M-row table at 100 rows per 8 KB page is ~100k pages. A predicate matching 5% of rows touches 500k rows; if they are scattered, that is up to ~500k random page reads against ~100k sequential reads for the full scan: the planner picks the scan, correctly. The crossover moves with row width, physical correlation, and storage: on SSD the random-read penalty shrinks and the crossover sits at a higher selectivity. Stale statistics are the usual culprit when a sargable predicate gets the wrong plan: run ANALYZE and compare estimated against actual rows in EXPLAIN ANALYZE.

Detecting it. In Postgres, EXPLAIN (ANALYZE, BUFFERS) and look for Index Scan / Index Only Scan versus Seq Scan; a Filter: line repeating your expression means it was not pushed into the index condition. In SQL Server, the plan shows a Scan with a residual predicate instead of a Seek Predicate.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-13

How would you approach a report query that has become too slow?

Answer

I measure before changing anything. EXPLAIN ANALYZE gives the actual plan with real timings and row counts, which tells me where the time goes instead of where I guess it goes.

The first thing I look for is a large gap between estimated and actual rows. That mismatch is usually the root cause: the planner chose a nested loop expecting fifty rows and got fifty thousand. Stale statistics, a correlated predicate the planner cannot model, or an expression that hides the column from the estimator all cause it. Refreshing statistics sometimes fixes the whole problem.

Then I look for the specific expensive shapes: a sequential scan on a large table under a selective predicate, which suggests a missing or unusable index; a sort that spills to disk, which suggests either a missing index matching the sort order or too little working memory; and a nested loop over a large outer input where a hash join belongs.

On indexes, the common defect is a non-sargable predicate (wrapping the column in a function, or a leading wildcard in LIKE) which makes an existing index unusable. Rewriting the predicate to leave the column bare, or building an expression index, restores it. A common starting heuristic for composite indexes is equality predicates first, then a range or ordering column, but the final order must be verified against the engine, data distribution and actual plan.

Before adding an index I check the query itself: unnecessary DISTINCT hiding fan-out, a join that could be EXISTS, SELECT * preventing an index-only scan, OFFSET pagination that should be keyset. Fixing the query is usually better than indexing around it, because every index has a write cost.

If the query is genuinely aggregating millions of rows for a dashboard, the honest answer may be that it should not run on demand: a materialized view or incremental rollup refreshed on a schedule is the right shape. Then I re-measure and confirm against production-like data volumes.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-11

A query returns correct results in testing but wrong ones in production. What do you check?

Answer

My first assumption is that the query encodes an assumption production data violates, so I look for the assumptions rather than at the SQL line by line.

NULLs first, because they fail silently. Test fixtures are usually fully populated; production has NULLs in nullable columns. A NOT IN over a column that is never NULL in test but sometimes NULL in production returns zero rows with no error. Equality comparisons against NULL match nothing. I check every nullable column the query touches.

Cardinality second. Test data often has one child per parent, so fan-out never shows. Production has customers with two hundred orders, and any aggregate over the joined result inflates. I count rows before and after each join on real data.

Missing ORDER BY third. If the query has a LIMIT without a total ordering, test returned a stable order by coincidence of a small table and a sequential scan; production picks a different plan and returns different rows. Ties in a non-unique sort column do the same thing.

Then the environmental differences: collation and case sensitivity affecting comparisons and sorting; time zone settings changing what 'today' means for a date-bounded report; and the session's isolation level or a long-running transaction reading a snapshot older than expected.

Methodologically I reproduce against a production-like copy rather than reasoning from the test database, and I bisect: strip the query to its core and add clauses back until the result changes. That finds the offending clause faster than staring at the whole statement.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-5

Compare OFFSET and keyset pagination for a large, frequently updated list.

Answer

The 60-second answer

For a large, frequently updated list, use keyset pagination. OFFSET's cost grows with the page number because the engine produces and discards every skipped row, and its page boundaries move when rows are inserted or deleted between requests. Keyset carries the last row's sort key and seeks straight to it, so page 50,000 costs the same as page 1 and concurrent writes elsewhere cannot shift the boundary. The price is that you lose random access to page N, and you need a unique, indexed sort key.

Why OFFSET costs what it does

SELECT ... ORDER BY created_at DESC, id DESC LIMIT 50 OFFSET 100000 walks the index in order, emits 100,050 rows, discards 100,000, returns 50. Work is O(offset + limit), not O(limit). Illustrative figures for a 10M-row table on Postgres 16 with an index on (created_at, id) and a warm cache:

queryrows discarded by Limitshared bufferstime
OFFSET 0080.08 ms
OFFSET 100000100000~4,10042 ms
OFFSET 10000001000000~41,000380 ms

Why OFFSET is unstable

Rows in created_at DESC order: A, B, C, D. Page 1 (LIMIT 2) returns [A, B]. The user requests page 2 with OFFSET 2. Meanwhile X is inserted with a created_at newer than A. New order: X, A, B, C, D. OFFSET 2 now returns [B, C]: B is shown twice and D is never shown. A delete instead of an insert makes a row vanish unseen.

Keyset

SQL
SELECT id, created_at, title
FROM items
WHERE (created_at, id) < (:last_created_at, :last_id)
ORDER BY created_at DESC, id DESC
LIMIT 50;

The row-value comparison is what makes this correct. The expanded form is created_at < :last_created_at OR (created_at = :last_created_at AND id < :last_id); the tuple form lets the planner treat the composite index as a single seek instead of a filter over the created_at range. Index it with CREATE INDEX ON items (created_at DESC, id DESC), or plain (created_at, id), which Postgres can scan backwards. Cost is one index seek plus 50 rows, O(limit) at any depth.

Stability comes from the cursor being a value, not a position. Insert X above the cursor and page 2 still starts after (last_created_at, last_id): no duplicate, no skip. Delete the cursor row itself and the comparison still works, because you compare values rather than row identity.

Trade-offs and when not to use it

  • No random access. There is no "jump to page 7"; you get next and previous. Previous means reversing the comparison and the ORDER BY, then reversing the result client-side: WHERE (created_at, id) > (:first_created_at, :first_id) ORDER BY created_at ASC, id ASC LIMIT 50.
  • No cheap total count. COUNT(*) over the filtered set is a separate full scan, so "page 3 of 812" is not available.
  • The sort key must be unique and indexed. A non-unique created_at alone lets ties straddle the boundary and rows get skipped or repeated; append the primary key.
  • The cursor must be opaque and signed. Exposing raw (created_at, id) lets a client forge a cursor; base64-encode it with an HMAC and validate the decoded values.
  • Changing the sort order mid-scroll invalidates the cursor: reject it and restart.
  • OFFSET is fine when the list is small (a few thousand rows) or the user genuinely needs page numbers, such as an admin table with a page selector.

Failure modes and how to detect them

  • Missing tiebreaker: duplicates or skips at page boundaries. Test by inserting a row between two page fetches and asserting the two pages do not overlap.
  • Filter not covered by the index: keyset stays correct but the seek degrades to a scan. Check EXPLAIN for an Index Scan rather than a Seq Scan.
  • Cursor tampering: an unsigned cursor allows arbitrary reads. Fuzz the cursor parameter and assert rejection.
  • OFFSET under concurrent writes: run a load test with concurrent inserts and assert page N and page N+1 share no rows.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-18

How do you write a query whose results are stable and reproducible?

Answer

Nondeterminism comes from four places, and I check each.

Ordering first. Without ORDER BY there is no guaranteed order at all, not insertion order, not primary key order. A LIMIT without a total ordering returns arbitrary rows, and pagination built on it skips and repeats. Crucially, an ORDER BY on a non-unique column is only partially deterministic: rows tied on that column may come back in any relative order, and will differ between runs and plans. So a deterministic ordering means appending a unique tiebreaker, normally the primary key.

Second, engine-specific latitude. Selecting a column that is neither grouped nor aggregated is either an error or returns an arbitrary row from the group, depending on the engine, if I want a specific row, I say so with DISTINCT ON or ROW_NUMBER.

Third, time and session context. now() and CURRENT_DATE make the result depend on when it ran, and a report bounded by 'today' depends on the session time zone. For reproducibility I pass explicit bounds as parameters rather than computing them inside the query, and store timestamps in UTC.

Fourth, concurrency. A long report running in read-committed isolation can see different snapshots between statements. Running it in a repeatable-read transaction gives one consistent snapshot throughout.

For genuinely reproducible output, a regression test or a data export, I fix all four: explicit parameters instead of now(), a total ordering including the tiebreaker, a stated isolation level, and a pinned collation if text sorting matters, since collation changes reorder text results across environments.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-20

How would you safely add a NOT NULL column to a large, live table?

Answer

The naive statement (add the column, NOT NULL, with a default, in one step) is the one that causes an outage on an older engine, because it rewrites every row while holding an exclusive lock. Modern PostgreSQL stores a non-volatile default in the catalogue and avoids the rewrite, but I do not rely on version-specific behaviour for a table that matters; I use a sequence that is safe regardless.

The expand–migrate–contract sequence: first add the column as nullable with no default, which is a fast catalogue-only change. Second, deploy application code that writes the new column on every insert and update but does not yet require it to be present when reading: the two must be separate deploys, because during the rollout both old and new code are running. Third, backfill existing rows in bounded batches with a pause between them, so no single transaction holds locks for long or generates an unmanageable amount of WAL. Fourth, once no NULLs remain, add the constraint: using a NOT VALID check constraint validated separately where the engine supports it, so the validation scan does not block writes. Finally, deploy code that depends on the column being present.

Throughout I keep each step independently reversible. The rule that makes rollback safe is that no deployed version may require a schema element that a version it might roll back to does not tolerate, which is precisely why the write step and the read step are separate releases.

I rehearse on a production-sized copy, measure the backfill rate and lock behaviour there, monitor replication lag during the real run because a large backfill can push replicas behind, and pick a low-traffic window. If the table is enormous and the engine cannot avoid a rewrite, a shadow table with triggered dual-writes and an atomic rename is the fallback.

Curated: · Written: · Reviewed:

Difficulty: Hard