SQL Interview Patterns

Listen for the signal words, name the pattern, then adapt the template. State the grain and the tie rule before you write.

SQL interview patterns cheat sheet: signal words and query templates for top N per group, running totals, gaps and islands, funnels and MERGE
Printed sheet title: SQL interview patterns

What the sheet covers

A compact reference of query templates, not a list of interview questions. Each social card groups patterns from the typographic sheet: top N per group and latest row per key, running totals (one row per day in the template), gaps and islands and sessions, funnels and cohort retention (the first buy must come at or after the first view), MERGE upserts and SCD Type 2 history, and source-to-target reconciliation (assumes one non-NULL id per side; FULL JOIN is not MySQL; EXCEPT is set semantics). State the grain and the tie rule before you write the SQL. For practice problems, see the book rather than this page.

Topics on the sheet

  • Top N per group, and latest row per key
  • Running total
  • Gaps and islands, and sessions
  • Funnel and cohort retention
  • Upsert (MERGE) and SCD type 2
  • Reconciliation

Download the PDF

SQL interview patterns as a one-page PDF in Letter and A4, plus all six sheets in one SQL cheat sheet PDF. Free PDF, download it right after you sign up. Signing up joins the dataengineers.club newsletter and unlocks the PDF bundle in Letter and A4. Unsubscribe anytime.

Top N per group, and latest row per key

Signal words: top 3 per, highest in each, best-selling by, latest, current status, remove duplicates.

SELECT * FROM (
  SELECT o.*, DENSE_RANK() OVER (
    PARTITION BY customer_id
    ORDER BY amount DESC) AS r
  FROM orders o
) t
WHERE r <= 3;

-- latest row
SELECT * FROM order_log
QUALIFY ROW_NUMBER() OVER (
  PARTITION BY order_id
  ORDER BY ts DESC, load_id DESC) = 1;

DENSE_RANK keeps ties. ROW_NUMBER returns at most 3. Tiebreak on a unique load or event id. DuckDB also: arg_max(status, ts) with GROUP BY, but it skips NULL statuses and NULL timestamps; tied timestamps need a unique tie-breaker (Q24).

Running total

Signal words: cumulative, to date, running.

SELECT day, amount,
  SUM(amount) OVER (
    ORDER BY day
    ROWS UNBOUNDED PRECEDING
  ) AS running
FROM daily;

Assumes one row per day. Month to date: add PARTITION BY date_trunc('month', day).

Gaps and islands, and sessions

Signal words: consecutive days, streak, in a row, session, 30 minutes of inactivity, visit.

Day minus row number is constant inside a run. For sessions, LAG flags a new session when the gap is over 30 minutes. A gap of exactly 30 minutes stays in the session. id makes tied timestamps stable.

-- islands: day - ROW_NUMBER() AS grp
-- sessions:
CASE WHEN ts - LAG(ts) OVER (
    PARTITION BY user_id ORDER BY ts, id)
  <= INTERVAL '30 minutes'
THEN 0 ELSE 1 END AS new_s

Funnel and cohort retention

Signal words: conversion, drop-off, step 1 to step 2, retention, cohort, came back in month N.

-- funnel: first buy must come at or after first view
COUNT(CASE WHEN t_buy >= t_view THEN 1 END) AS bought

-- retention
datediff('month', f.cohort, a.m) AS month_n
-- rate: divide by the month 0 count of the same cohort

Rate: 1.0 * bought / NULLIF(viewed, 0).

Upsert (MERGE) and SCD type 2

Signal words: load new and changed rows, safe to rerun, history, as of a date, point in time.

MERGE INTO dim t
USING stg s ON t.id = s.id
WHEN MATCHED THEN UPDATE SET name = s.name
WHEN NOT MATCHED THEN INSERT (id, name)
  VALUES (s.id, s.name);

-- SCD2 as-of time t:
-- valid_from <= t AND (valid_to > t OR valid_to IS NULL)

Dedup stg to one row per id first. PostgreSQL also: INSERT ... ON CONFLICT (id) DO UPDATE. MySQL: ON DUPLICATE KEY UPDATE. Run the SCD2 close and insert in one transaction. Assumes one stg2 row per id, newer than the current version.

Reconciliation

Signal words: compare source and target, missing rows.

SELECT COALESCE(s.id, t.id) AS id,
  CASE
  WHEN t.id IS NULL THEN 'missing'
  WHEN s.id IS NULL THEN 'extra'
  WHEN s.amt IS DISTINCT
       FROM t.amt THEN 'changed'
  ELSE 'ok'
  END AS status
FROM src s
FULL JOIN tgt t ON t.id = s.id;

Assumes one non-NULL id per side. Compare COUNT(*) and SUM(amt) first. Quick diff: src EXCEPT tgt (set semantics hide duplicate counts; use EXCEPT ALL where it exists), then the other way. FULL JOIN is not MySQL.

Engines named on the sheet

DuckDB, PostgreSQL, MySQL. Named on the cards: DuckDB (arg_max on the latest-row card), PostgreSQL (ON CONFLICT) and MySQL (ON DUPLICATE KEY UPDATE) on the upsert card. Other engines are not named on this sheet. DuckDB 2.0.1 is the runtime used in the book. Do not read this list as a claim that every engine was executed for every example.

FAQ

Is this a list of SQL interview questions?

No. It is a reference of query templates. For practice problems, use the book.

DENSE_RANK or ROW_NUMBER for top N per group?

DENSE_RANK keeps ties, so it can return more than N rows. ROW_NUMBER returns at most N. Add a tiebreak on a unique load or event id.

How does the gaps and islands pattern work?

Day minus row number is constant inside a run of consecutive days, so you group by that value to find each island.

What does the reconciliation template assume?

One non-NULL id per side. Compare COUNT(*) and SUM(amt) first. EXCEPT uses set semantics, so it hides duplicate counts; use EXCEPT ALL where it exists. FULL JOIN is not available in MySQL.

© 2026 Vincent Charles. License: CC BY-NC-ND 4.0. You may share this page with credit. Do not sell the sheets or share modified versions.

SQL cheat sheets by Vincent Charles, from SQL Interview Questions for Data Engineers. dataengineers.club