The 20 SQL patterns that repeat across analyst, backend and data rounds — ranking, joins, aggregation, and gaps-and-islands.
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.