17 SQL Interview Patterns (and the 5 Families Behind Them)
The SQL patterns that show up most in interviews: ranking, running totals, recursive CTEs, gaps and islands, and CASE pivots. Each with the query shape and a drill.
Why patterns beat memorizing questions
You will not see the same question twice. You will see the same shapes over and over: “the top 3 per category,” “the running total,” “the streak of consecutive days.” Learn to name the shape from the wording, and the query mostly writes itself.
The examples below use MySQL syntax, which is what many interviews use. The practice shop (customers, orders, order_items, products) does not have a manager column or a login table, so those two examples are illustrative.
Family 1 — Ranking: top N per group, and the Nth highest
When the question says “top” or “highest,” and the answer must be a row per group, you want a window function and a filter on the result.
SELECT name, category, price
FROM (
SELECT name, category, price,
ROW_NUMBER() OVER (PARTITION BY category ORDER BY price DESC) AS rn
FROM products
) ranked
WHERE rn <= 3;
For the 2nd highest distinct value, use DENSE_RANK() and filter to 2. ROW_NUMBER() breaks ties arbitrarily; RANK() skips numbers after a tie. Know which one the question needs.
Drill: rank within category. Guide: top N per group.
Family 2 — Running totals, LAG, and moving averages
Running totals and period-over-period growth both use windows over an ordered column. First build one row per day, then apply the window.
WITH daily AS (
SELECT o.order_date, SUM(oi.qty * p.price) AS revenue
FROM orders o
JOIN order_items oi ON oi.order_id = o.order_id
JOIN products p ON p.product_id = oi.product_id
WHERE o.status = 'paid'
GROUP BY o.order_date
)
SELECT order_date,
revenue,
SUM(revenue) OVER (ORDER BY order_date) AS running_total,
LAG(revenue) OVER (ORDER BY order_date) AS previous_day,
AVG(revenue) OVER (ORDER BY order_date
ROWS BETWEEN 6 PRECEDING AND CURRENT ROW) AS avg_last_7_rows
FROM daily;
The gotcha: ROWS BETWEEN 6 PRECEDING means seven rows, not seven days. If the shop has no sales on a Sunday, that Sunday is missing from the table, and seven rows can span eight or more days. If quiet days should count as zero, generate every date first (a calendar table or a recursive CTE), left join your daily revenue onto it, and then apply the window.
Guide: how window functions work.
Family 3 — Recursive CTEs: walking a hierarchy
Employee and manager trees, category trees, and org charts all need a query that walks down (or up) a chain of unknown depth. A recursive CTE has two parts: a starting row, and a step that joins back to itself.
WITH RECURSIVE chain AS ( SELECT employee_id, manager_id, name, 1 AS depth FROM employees WHERE manager_id IS NULL UNION ALL SELECT e.employee_id, e.manager_id, e.name, c.depth + 1 FROM employees e JOIN chain c ON e.manager_id = c.employee_id ) SELECT * FROM chain;
Say the two parts out loud in the interview: the anchor finds the top, the recursive step finds the next level down. Guide: how CTEs work. Drill on the non-recursive version first: a CTE on paid orders.
Family 4 — Gaps and islands: consecutive days
“Find each user’s login streaks” is the classic. The trick: for consecutive dates, the date minus its row number stays the same. Equal results form one island.
WITH days AS (
SELECT DISTINCT user_id, login_date FROM logins
),
numbered AS (
SELECT user_id, login_date,
ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY login_date) AS rn
FROM days
),
islands AS (
SELECT user_id, login_date,
DATE_SUB(login_date, INTERVAL rn DAY) AS island_id
FROM numbered
)
SELECT user_id,
MIN(login_date) AS streak_start,
MAX(login_date) AS streak_end,
COUNT(*) AS streak_days
FROM islands
GROUP BY user_id, island_id
ORDER BY streak_days DESC;
Remove the DISTINCT and a user who logs in twice in one day breaks their own streak. This is the pattern most candidates miss under pressure, so drill it until the three CTEs feel routine.
Family 5 — Advanced joins and CASE pivots
Self-joins compare a row with another row in the same table (an employee and their manager). Pivots turn row values into columns with CASE inside an aggregate:
SELECT c.city,
SUM(CASE WHEN o.status = 'paid' THEN 1 ELSE 0 END) AS paid_orders,
SUM(CASE WHEN o.status = 'cancelled' THEN 1 ELSE 0 END) AS cancelled_orders
FROM customers c
JOIN orders o ON o.customer_id = c.customer_id
GROUP BY c.city;
Cohort retention is the same idea with a join on “the month of first order.” Compute each customer’s first month in a CTE, join it back to the orders, then count distinct active customers per cohort and month.
Drills: CASE for a status flag · Guides: self-join, CASE WHEN.
Recognize the pattern from the wording
- “top N per …”, “2nd highest …” → ranking (ROW_NUMBER / DENSE_RANK + filter)
- “running …”, “previous …”, “last 7 …” → windows (SUM, LAG, AVG with a frame)
- “all levels of …”, “every manager above …” → recursive CTE
- “consecutive …”, “streak …” → gaps and islands
- “by status”, “pivot”, “breakdown per …” → CASE inside an aggregate
Say the pattern out loud before typing. Interviewers reward the naming as much as the query.
Watch the walkthrough
I recorded a step-by-step video that solves each of these 17 patterns with the exact queries and an explanation of why each one works. The dataset and script are included so you can practice alongside it:
SQL Interview Questions & Answers MySQL 17 Must Know Patterns
Then drill the same shapes on the practice shop: rank products by price, 15 common interview questions, and the interview prep path.
FAQ
What SQL patterns come up most in interviews?
Top N per group (ROW_NUMBER or RANK), running totals and moving averages, recursive CTEs for hierarchies, gaps and islands for consecutive days, and CASE-based pivots. Most questions are one of these with a different business story.
Why learn patterns instead of memorizing questions?
Interview questions are rewritten all the time, but the shape of the answer repeats. Once you recognize a pattern from the wording, the query is mostly filling in column names.
Try it yourself
The fastest way to lock this in is a short drill on the same Northstar Market tables.
Practice ranking inside a group