Solving Classic FAANG / Senior Data Analyst SQL Interview Problems
Practice senior-level SQL interview patterns: Top-N, retention, gaps, and windows.
In plain words
Most hard SQL questions are a few familiar puzzles in disguise. Spot which puzzle it is, then solve it step by step.
Think of it like…
Chess openings: strong players don't calculate every move from scratch. They recognise the position ("this is a top-N-per-group problem") and play a known structure, saving their thinking for the details that differ.
Where you’ve seen it
"What share of users who signed up in January came back the next day?" is a retention problem: find each user's first activity date, check for activity on first_date + 1, and divide retained users by cohort size per signup date.
Words you’ll hear
- Pattern
- A reusable solution shape: ranking, LAG comparison, gaps and islands, anti-join, cohort.
- Grain
- What one row of each intermediate step means. Stating it prevents most bugs.
- Edge cases
- Ties, NULLs, duplicates, missing days, timezones and partial periods.
- Cohort
- A group of users defined by when they started, used for retention analysis.
Visual diagram
Theory & example queries
The pattern map
Ranking: Nth highest → DENSE_RANK; one row per group (latest, best) → ROW_NUMBER = 1; top-N per group → ROW_NUMBER ≤ N with PARTITION BY. Comparison with a previous period or event: aggregate, then LAG. Consecutive runs (streaks, sessions): gaps and islands, or LAG plus a running sum of "new session" flags. Did X but not Y: NOT EXISTS. Share of total: value / SUM(value) OVER (). Median: PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY x).
Retention and cohorts: find each user's first date, join back to activity at first_date + k, and divide retained users by cohort size. Mutual relationships (friends who follow each other): self join with a.user = b.target AND a.target = b.user, keeping each pair once with a.user < a.target.
| id | created_at | archived |
|---|---|---|
| 1 | 2024-11-20 | false |
| 2 | 2024-12-15 | false |
| 3 | 2026-01-05 | false |
WITH f AS ( SELECT user_id, MIN(event_date) AS d0 FROM events GROUP BY user_id )SELECT f.d0, COUNT(DISTINCT f.user_id) AS cohort, COUNT(DISTINCT e.user_id) AS retained_d1FROM f LEFT JOIN events e ON e.user_id = f.user_id AND e.event_date = f.d0 + 1GROUP BY f.d0;PostgreSQL is the lesson baseline unless noted otherwise.
Read this line together with the surrounding statement as part of the same SQL expression.
Expected output3 sample rows
| d0 | cohort | retained_d1 |
|---|---|---|
| 2026-11-01 | 1000 | 360 |
| 2026-11-02 | 1240 | 421 |
| 2026-11-03 | 980 | 319 |
Note: Illustrative first-event cohorts and next-day retention counts.
COUNT(DISTINCT e.user_id) skips the NULLs from users who didn't return, and DISTINCT absorbs multiple events on day 1.
Key takeaway: Name the pattern out loud; most of the solution follows.
How to run the interview
Clarify before typing: the output grain ("one row per user per month?"), how ties count, whether NULLs or test accounts are excluded, the timezone of dates, and whether the current partial period is included. Interviewers often leave these ambiguous on purpose.
Write the solution as named CTEs, one step each, and state each step's grain. Walk through a 3–5 row example to check it, including a tie and a NULL. Finish with complexity and indexing: what would you index, and what changes at a billion rows (pre-aggregation, approximate distinct counts, partitioning)?
| id | customer_id | status | amount | coupon_code |
|---|---|---|---|---|
| 101 | 1 | paid | 249 | NULL |
| 102 | 2 | paid | 120 | WELCOME10 |
| 103 | 1 | shipped | 89.5 | NULL |
SELECT DISTINCT o.user_idFROM orders oWHERE o.created_at >= '2026-01-01' AND o.created_at < '2026-02-01' AND NOT EXISTS ( SELECT 1 FROM orders o2 WHERE o2.user_id = o.user_id AND o2.created_at >= '2026-02-01' AND o2.created_at < '2026-03-01' );PostgreSQL is the lesson baseline unless noted otherwise.
Calculate the selected expressions and return the requested output columns.
Expected output3 sample rows
| user_id |
|---|
| 104 |
| 219 |
| 887 |
Note: Illustrative users who ordered in January 2026 but had no order in February 2026.
Key takeaway: Clarify, build in steps, test with a tiny example, then talk about scale.
How it works, step by step
Follow one practical SQL workflow from start to finish. Select any step or play through the flow.
Clarify the question
Confirm the output grain, tie rules, NULL handling, time range, timezone and whether partial periods count.
"One row per user? Ties included?"
When to use it & trade-offs
What it is
Senior SQL interview problems at large tech companies are built from a small set of recurring patterns: ranking (Nth highest, top-N per group), period comparisons (growth, retention), sequences (streaks, sessions), set logic (did X but not Y), and deduplication. Recognising the pattern quickly, then solving it in clear CTE steps while handling edge cases, is what's being assessed.
Why it matters: These interviews rarely test obscure syntax. They test whether you can turn a vague business question into the right grain, spot traps (ties, NULLs, fan-out, partial periods) and explain trade-offs. A repeatable approach matters more than memorising answers.
When to reach for it
- Preparing for data analyst, data scientist and data engineer SQL rounds
- Structuring any multi-step analytics query
- Explaining your reasoning while writing SQL live
When to avoid or be careful
- Writing SQL before clarifying the grain and edge cases
- One giant nested query instead of named steps
- Stopping at "it runs" without testing ties, NULLs and duplicates
Common patterns and their tools
Strengths: DENSE_RANK / ROW_NUMBER with PARTITION BY handles it cleanly.
Watch out: Must decide how ties are treated.
Strengths: LAG / LEAD or a join on shifted dates.
Watch out: Needs a gap-free series and fair periods.
Strengths: NOT EXISTS; gaps and islands; running-sum session flags.
Watch out: Deduplicate input and watch for NULLs.
Interview signals & numbers to know
When this topic comes up
- “Second highest salary”
- “Users who did X but not Y”
- “Day-7 retention”
- “Longest streak”
- “Month-over-month growth”
Benchmarks & rules of thumb
- ~6
- patterns cover most interview problems
- 3–5 rows
- enough for a test example
- 1 CTE
- per logical step
Common mistakes & follow-ups
Common interview mistakes
- Jumping straight into SQL and solving a different question than the one asked.
- Ignoring ties or NULLs, which the interviewer then uses as the follow-up.
- Joining several one-to-many tables at once and producing inflated counts.
Likely interviewer follow-ups
- How would you compute 7-day retention for each weekly signup cohort?
- How would you find users whose activity dropped by more than 50% month over month?
- Your query is correct but slow on a billion rows. What would you change?
Knowledge check
Put it into practice
Practice related interview Q&A
Apply Solving Classic FAANG / Senior Data Analyst SQL Interview Problems with hands-on SQL practice and interview Q&A.