BTI Beyond The Interviews

Databases · 8 sections

SQL Interview Puzzles

The 20 SQL patterns that repeat across analyst, backend and data rounds — ranking, joins, aggregation, and gaps-and-islands.

Premium · preview 56 cards Updated 24 Oct 2026
Free to preview. The first 3 cards and the full outline are below — the rest of this sheet is part of the Backend, Databases & AI bundle.

What's inside

Preview — first 3 of 56 cards

Second-highest salary (return NULL if none).

Filter out the maximum and take the maximum of what remains — this handles ties correctly. A `DENSE_RANK()` version generalises to the Nth value. Returns NULL when there is no second salary.

SELECT MAX(salary)
FROM emp
WHERE salary < (SELECT MAX(salary) FROM emp);

Nth highest salary per department.

Rank within each department using `DENSE_RANK()` (ties share a rank, so N = 3 is the 3rd distinct salary), then filter. Swap in `ROW_NUMBER()` for exactly one row per department, or `RANK()` to leave gaps after ties.

SELECT *
FROM (
  SELECT e.*,
         DENSE_RANK() OVER (PARTITION BY dept ORDER BY salary DESC) AS r
  FROM emp e
) t
WHERE r = 3;

Running total of daily revenue.

A window aggregate over a growing frame. The explicit `ROWS` frame keeps the result deterministic when several rows share the same `day`.

SELECT day, amount,
       SUM(amount) OVER (
         ORDER BY day
         ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
       ) AS running_total
FROM revenue;

53 more cards in this sheet

Unlock the Backend, Databases & AI bundle — ₹399

One-time payment. Unlocks this sheet and 14 other sheets in the bundle, plus a typeset PDF of each.

Unlock the bundle See all bundles

Or get all 76 sheets for ₹999 — one payment, every future sheet included.