SQL Interview Problem Patterns
Difficulty: Hard | Companies: Google, Amazon, Meta, Netflix, Uber
How these problems are recognized
There is a repeatable shape to SQL interview questions. Almost every prompt is one of six things wearing a different costume: a ranking problem, a running aggregate, a grouping of consecutive events, a reshape, a session boundary, or a percentile. Recognizing the shape in the first thirty seconds matters more than typing quickly, because the shape decides whether you reach for a window function, a self-join, a recursive CTE, or a lateral scan. Read the prompt for three signals: what defines a group, what defines order inside that group, and what the interviewer expects when ties appear. Ties are where most candidates lose the round. The choice between ROW_NUMBER, RANK, and DENSE_RANK changes the answer set, and stating which one you picked and why is frequently the actual question being asked.
Top N Per Group
-- Find top 3 earners per department
SELECT
department_id,
employee_id,
name,
salary,
DENSE_RANK() OVER (
PARTITION BY department_id ORDER BY salary DESC
) AS rank
FROM employees
QUALIFY rank <= 3; -- BigQuery syntax
-- PostgreSQL alternative
SELECT *
FROM (
SELECT
department_id,
employee_id,
name,
salary,
ROW_NUMBER() OVER (
PARTITION BY department_id ORDER BY salary DESC
) AS rn
FROM employees
) sub
WHERE rn <= 3;
âšī¸
Key Insight: Use ROW_NUMBER() for exactly N rows, DENSE_RANK() to include ties, and RANK() to skip ranks after ties. BigQuery's QUALIFY clause simplifies filtering window function results.
Once the ranking function is chosen, decide where the filter lives. Wrapping the window in a derived table and filtering outside is portable across engines; BigQuery and Snowflake accept QUALIFY, which keeps the logic in one place and avoids a second pass over the result. Ordering inside the partition must be deterministic â add a unique tiebreaker such as employee id after salary, otherwise two runs of the same query can return different employees and a nightly job will flap between answers. Watch the three functions closely with the values 5, 5, 3, 1 when the interviewer asks for the top two.
| Function | Ranks assigned | Rows kept at rank less than or equal to 2 | What it means |
|---|---|---|---|
| ROW_NUMBER | 1, 2, 3, 4 | 2 | Exactly two rows, one tied value discarded |
| RANK | 1, 1, 3, 4 | 2 | Both leaders kept, nothing occupies rank 2 |
| DENSE_RANK | 1, 1, 2, 3 | 3 | Both leaders plus the next distinct value |
Expect the harder variant immediately after you get this right: top N per group where the group itself comes from a join, which usually means materializing the ranking in a CTE before filtering.
Running Total with Reset
-- Running total that resets at specific boundaries
SELECT
department_id,
employee_id,
salary,
hire_date,
SUM(salary) OVER (
PARTITION BY department_id
ORDER BY hire_date
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
) AS dept_running_total,
SUM(salary) OVER (
PARTITION BY department_id, DATE_TRUNC('month', hire_date)
ORDER BY hire_date
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
) AS monthly_running_total
FROM employees
ORDER BY department_id, hire_date;
The window frame clause is the part candidates skip. ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW counts physical rows, so ties in the ordering column are summed in whatever order the engine happens to produce them, while RANGE takes every peer with the same key, which is what you want when several hires share a date. Partitioning decides where the total resets: one partition per department restarts the accumulation at each department, and adding the truncated month to the partition list restarts it again per month. When an interviewer asks for a running total that resets at a boundary, the answer is always the same shape â partition by the boundary, order by the timestamp, and state the frame out loud instead of hoping the default is correct.
Gap and Island
-- Find consecutive days of activity
WITH numbered AS (
SELECT
user_id,
activity_date,
activity_date - ROW_NUMBER() OVER (
PARTITION BY user_id ORDER BY activity_date
)::INT AS island_id
FROM user_activity
)
SELECT
user_id,
MIN(activity_date) AS streak_start,
MAX(activity_date) AS streak_end,
COUNT(*) AS streak_length
FROM numbered
GROUP BY user_id, island_id
HAVING COUNT(*) >= 3
ORDER BY user_id, streak_start;
Gap and island answers one specific question: which spans of consecutive activity exist. Subtract a dense row number from the date so that consecutive days produce a constant difference, then group on that constant. The trick only works if gaps are exactly one unit, so a weekend break in daily data is a gap you usually close by stepping in weeks or by filtering to business days before numbering. In an interview, state the invariant before you type: if the value increments by one per row, the subtraction yields one island per streak and the length of the streak is the row count. Then ask whether streaks may wrap across users or sessions, because partitioning by the wrong key silently merges unrelated activity into a single run.
Pivoting Data
-- Convert rows to columns
SELECT
department_id,
SUM(CASE WHEN EXTRACT(QUARTER FROM hire_date) = 1 THEN 1 ELSE 0 END) AS q1_hires,
SUM(CASE WHEN EXTRACT(QUARTER FROM hire_date) = 2 THEN 1 ELSE 0 END) AS q2_hires,
SUM(CASE WHEN EXTRACT(QUARTER FROM hire_date) = 3 THEN 1 ELSE 0 END) AS q3_hires,
SUM(CASE WHEN EXTRACT(QUARTER FROM hire_date) = 4 THEN 1 ELSE 0 END) AS q4_hires
FROM employees
WHERE EXTRACT(YEAR FROM hire_date) = 2024
GROUP BY department_id;
Conditional aggregation is the portable pivot. One pass over the table, one SUM(CASE WHEN ...) per output column, and the engine keeps a single scan instead of self-joining four times. The cost is that new buckets need new expressions, so for a moving window of columns generate the expressions in a script rather than hand-editing the query. Real pivot questions usually carry a second requirement: a total column, a share of the row, or the same pivot restricted to one region. Compute numerator and denominator from the same filtered set, otherwise the percentages will not reconcile with the column totals, and reconciliation is the first thing a reviewer checks.
Sessionization
-- Group events into sessions (30-min gap = new session)
WITH events_with_gap AS (
SELECT
user_id,
event_time,
LAG(event_time) OVER (
PARTITION BY user_id ORDER BY event_time
) AS prev_event_time
FROM events
),
session_assignments AS (
SELECT
*,
SUM(
CASE
WHEN event_time - prev_event_time > INTERVAL '30 minutes'
OR prev_event_time IS NULL
THEN 1
ELSE 0
END
) OVER (
PARTITION BY user_id ORDER BY event_time
) AS session_id
FROM events_with_gap
)
SELECT
user_id,
session_id,
MIN(event_time) AS session_start,
MAX(event_time) AS session_end,
COUNT(*) AS event_count
FROM session_assignments
GROUP BY user_id, session_id;
Sessionization turns a timestamp stream into rows a human would call sessions. The rule is a gap threshold: when the difference from the previous event exceeds the limit, start a new session, and the craft is turning that condition into a cumulative sum so it computes with one ordered window instead of a correlated lookup per row. Choose the threshold from the product rather than from habit â thirty minutes suits a content site, five minutes suits chat, and twenty-four hours suits a batch job that emits several events a day. Validate the choice by plotting session counts across a few thresholds: a curve that stays flat is not discriminating anything, and an interviewer who asks what you would measure is testing exactly that.
Median Calculation
-- Calculate median
SELECT
department_id,
PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY salary) AS median_salary
FROM employees
GROUP BY department_id;
-- Median with interpolation
SELECT
department_id,
PERCENTILE_DISC(0.5) WITHIN GROUP (ORDER BY salary) AS median_salary
FROM employees
GROUP BY department_id;
Year-over-Year Growth
-- Calculate YoY growth
WITH yearly_sales AS (
SELECT
EXTRACT(YEAR FROM order_date) AS year,
SUM(amount) AS total_sales
FROM orders
GROUP BY 1
)
SELECT
year,
total_sales,
LAG(total_sales) OVER (ORDER BY year) AS prev_year_sales,
ROUND(
(total_sales - LAG(total_sales) OVER (ORDER BY year)) * 100.0 /
NULLIF(LAG(total_sales) OVER (ORDER BY year), 0),
2
) AS yoy_growth_pct
FROM yearly_sales
ORDER BY year;
Percentiles deserve care. PERCENTILE_CONT interpolates between the two neighbouring salaries, so with an even count the median is a value nobody actually earns, while PERCENTILE_DISC returns an existing row instead. Both are ordered-set aggregates: they need an ORDER BY inside the function, and they cannot be derived from an already-aggregated table â a common failure when someone reaches for the median of group medians, which is mathematically wrong and will not match the median of the underlying rows. Year-over-year growth hides two more traps. The first year has no prior value, so the ratio is null rather than zero, and a shrinking denominator makes a small absolute change look enormous. Report the absolute delta beside the percentage and always guard the division.
Consecutive Numbers
-- Find numbers appearing at least 3 times consecutively
SELECT DISTINCT num AS ConsecutiveNums
FROM (
SELECT
num,
LAG(num) OVER (ORDER BY id) AS prev1,
LAG(num, 2) OVER (ORDER BY id) AS prev2
FROM logs
) sub
WHERE num = prev1 AND num = prev2;
Department Statistics
-- Comprehensive department analysis
SELECT
d.department_name,
COUNT(e.employee_id) AS emp_count,
AVG(e.salary) AS avg_salary,
STDDEV(e.salary) AS salary_stddev,
MAX(e.salary) - MIN(e.salary) AS salary_range,
PERCENTILE_CONT(0.25) WITHIN GROUP (ORDER BY e.salary) AS q1,
PERCENTILE_CONT(0.75) WITHIN GROUP (ORDER BY e.salary) AS q3
FROM departments d
LEFT JOIN employees e ON d.department_id = e.department_id
GROUP BY d.department_name
HAVING COUNT(e.employee_id) > 5
ORDER BY avg_salary DESC;
Consecutive-number detection reuses the lag trick: compare each row with the previous one and the one before it, then keep rows where all three agree. The subtlety is ordering â if ids have holes or rows can be deleted, three equal values in id order may not be three equal values in time order, so order by the timestamp and accept that ties break arbitrarily. Department statistics are the aggregation half of the same round: count, average, standard deviation, range, and quartiles in a single pass, filtered with HAVING rather than WHERE because the predicate applies to an aggregate. Ask whether departments with no employees should appear, because that decision changes an outer join into an inner join and turns a zero count into a missing row.
Recursive Hierarchy
-- Traverse organizational hierarchy
WITH RECURSIVE org_chart AS (
SELECT
employee_id,
name,
manager_id,
1 AS level,
name::TEXT AS path
FROM employees
WHERE manager_id IS NULL
UNION ALL
SELECT
e.employee_id,
e.name,
e.manager_id,
oc.level + 1,
oc.path || ' â ' || e.name
FROM employees e
INNER JOIN org_chart oc ON e.manager_id = oc.employee_id
)
SELECT * FROM org_chart ORDER BY path;
Complex Aggregation
-- Multiple aggregations in single query
SELECT
department_id,
COUNT(*) AS total_employees,
COUNT(*) FILTER (WHERE salary > 80000) AS high_earners,
COUNT(*) FILTER (WHERE hire_date > CURRENT_DATE - INTERVAL '1 year') AS new_hires,
SUM(salary) AS total_salary,
AVG(salary) FILTER (WHERE status = 'active') AS avg_active_salary
FROM employees
GROUP BY department_id;
Window Function with FILTER
-- Conditional window calculations
SELECT
department_id,
employee_id,
salary,
AVG(salary) FILTER (WHERE years_experience > 5)
OVER (PARTITION BY department_id) AS avg_senior_salary,
COUNT(*) FILTER (WHERE performance_rating >= 4)
OVER (PARTITION BY department_id) AS high_performer_count
FROM employees;
Complex Joins
-- Self-join for comparison
SELECT
e1.employee_id,
e1.name,
e1.salary,
e2.name AS manager_name,
e2.salary AS manager_salary,
e1.salary - e2.salary AS salary_difference
FROM employees e1
LEFT JOIN employees e2 ON e1.manager_id = e2.employee_id;
-- Cross join for combinations
SELECT
p.product_name,
s.store_name,
COALESCE(i.quantity, 0) AS stock
FROM products p
CROSS JOIN stores s
LEFT JOIN inventory i ON p.product_id = i.product_id
AND s.store_id = i.store_id;
String Aggregation
-- Aggregate strings with ordering
SELECT
department_id,
STRING_AGG(name, ', ' ORDER BY salary DESC) AS employees_by_salary
FROM employees
GROUP BY department_id;
-- BigQuery equivalent
SELECT
department_id,
STRING_AGG(name, ', ' ORDER BY salary DESC) AS employees_by_salary
FROM employees
GROUP BY department_id;
Complex Date Calculations
-- Find first and last day of month
SELECT
employee_id,
hire_date,
DATE_TRUNC('month', hire_date)::DATE AS first_day_of_month,
(DATE_TRUNC('month', hire_date) + INTERVAL '1 month - 1 day')::DATE AS last_day_of_month
FROM employees;
-- Calculate business days
SELECT
order_id,
order_date,
ship_date,
(ship_date - order_date) AS calendar_days,
(ship_date - order_date) - (
EXTRACT(DOW FROM ship_date) - EXTRACT(DOW FROM order_date)
) / 7 * 2 AS business_days_approx
FROM orders;
Structuring the answer out loud
Interviewers score reasoning, not keystrokes. A reliable shape for each problem takes about four minutes: restate the inputs and the grain, name which of the six pattern families it belongs to, write the query, then name one way it breaks on real data. Verbalizing the grain catches most mistakes before any code exists â a prompt that says top three earners per department already implies the partition key and the tie policy, and saying them out loud proves you heard both. Closing with a limitation, such as an unbounded recursion, a percentile that cannot be computed from partial aggregates, or a pivot that needs new expressions for every new bucket, signals production experience rather than tutorial familiarity. If you get stuck, narrate the alternative you rejected and why; partial reasoning scores better than silence followed by a correct answer.
Follow-Up Questions
- How would you optimize a query that's running slowly?
- What's the difference between WHERE and HAVING?
- Explain the concept of query plan and how to read it.
- How do you handle NULL values in SQL operations?
- What's the best approach for pagination in SQL?
- How would you implement a ranking system with ties?
Common Mistakes
Ranking with ROW_NUMBER when ties must share a position
Fix: Use RANK or DENSE_RANK and state which one the requirement calls for
Ordering a window by a non-unique column and expecting stable results
Fix: Append a unique tiebreaker such as an id so the plan and the answer stay deterministic
Computing a percentile from already-aggregated group values
Fix: Compute ordered-set percentiles from the base rows, never from averages or medians of medians
Best Practices
- Name the pattern family aloud before writing any SQL
- Partition by the group boundary and order by a unique column in every window
- Filter window results in a derived table or with QUALIFY, not with WHERE on the window itself
- Guard every ratio against a null denominator and report the absolute change beside the percentage
- Close each answer with one known limitation of the query you just wrote
Interview Questions
Q1: Which ranking function returns exactly N rows per group?
ROW_NUMBER, because it assigns unique consecutive positions; RANK and DENSE_RANK can return more than N rows when ties straddle the cutoff
Q2: Why might a running total be wrong with ties in the ordering column?
A ROWS frame sums physical rows, so tied keys accumulate in an engine-dependent order; a RANGE frame includes all peers together
Q3: How do you find streaks of consecutive activity?
Subtract a dense row number from the date so each streak collapses to a constant, then group on that constant and aggregate
Q4: What is the difference between PERCENTILE_CONT and PERCENTILE_DISC?
CONT interpolates between neighbours and can return a value that does not exist; DISC returns the first actual row at or above the requested percentile
Key Takeaways
- Every interview prompt maps to one of six families: rank, accumulate, streak, pivot, session, percentile
- Tie handling is the discriminator â choose ROW_NUMBER, RANK, or DENSE_RANK from the requirement
- Window frames and partition keys decide where totals reset and how peers are treated
- Percentiles must be computed from base rows, and every ratio needs a null guard
- A four-minute answer that names a limitation beats a silent query that happens to run