Interview's MateSQL Learning
Interview's Mate

SQL Learning

Foundations → production SQL

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
SQL topics
Lesson 100/ 160
05. Window Functions & Analytical SQL

Solving Classic FAANG / Senior Data Analyst SQL Interview Problems

Practice senior-level SQL interview patterns: Top-N, retention, gaps, and windows.

AdvancedInterview Patterns · Multi-Step SQL3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

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

Loading interactive 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.

Day-1 retention by signup dateQuery example
1Input dataStart from the source rows or state that the statement sees.
events
3 rows
events sample rows
idcreated_atarchived
12024-11-20false
22024-12-15false
32026-01-05false
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1WITH2  f AS (3    SELECT4      user_id,5      MIN(event_date) AS d06    FROM7      events8    GROUP BY9      user_id10  )11SELECT12  f.d0,13  COUNT(DISTINCT f.user_id) AS cohort,14  COUNT(DISTINCT e.user_id) AS retained_d115FROM16  f17  LEFT JOIN events e ON e.user_id = f.user_id18  AND e.event_date = f.d0 + 119GROUP BY20  f.d0;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · SQL expression

Read this line together with the surrounding statement as part of the same SQL expression.

1/20
3OutputInspect the representative rows, affected-row count, plan, or command status.
Expected output3 sample rows
Expected output
d0cohortretained_d1
2026-11-011000360
2026-11-021240421
2026-11-03980319

Note: Illustrative first-event cohorts and next-day retention counts.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

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)?

Users who bought in January but not in FebruaryQuery example
1Input dataStart from the source rows or state that the statement sees.
orders
3 rows
orders sample rows
idcustomer_idstatusamountcoupon_code
1011paid249NULL
1022paid120WELCOME10
1031shipped89.5NULL
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT DISTINCT2  o.user_id3FROM4  orders o5WHERE6  o.created_at >= '2026-01-01'7  AND o.created_at < '2026-02-01'8  AND NOT EXISTS (9    SELECT10      111    FROM12      orders o213    WHERE14      o2.user_id = o.user_id15      AND o2.created_at >= '2026-02-01'16      AND o2.created_at < '2026-03-01'17  );
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Project and calculate

Calculate the selected expressions and return the requested output columns.

1/17
3OutputInspect the representative rows, affected-row count, plan, or command status.
Expected output3 sample rows
Expected output
user_id
104
219
887

Note: Illustrative users who ordered in January 2026 but had no order in February 2026.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

Key takeaway: Clarify, build in steps, test with a tiny example, then talk about scale.

Interactive walkthrough

How it works, step by step

Follow one practical SQL workflow from start to finish. Select any step or play through the flow.

Progress1/4
Step 1You

Clarify the question

Confirm the output grain, tie rules, NULL handling, time range, timezone and whether partial periods count.

Focus at this step

"One row per user? Ties included?"

What to watch at this step
Time
1–2 minutes
Tip: use ← → to move between steps

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

Ranking (Nth highest, top-N, latest)
Best for: "Highest", "top 3", "most recent"

Strengths: DENSE_RANK / ROW_NUMBER with PARTITION BY handles it cleanly.

Watch out: Must decide how ties are treated.

Period and event comparisons
Best for: Growth, time between events, retention

Strengths: LAG / LEAD or a join on shifted dates.

Watch out: Needs a gap-free series and fair periods.

Set logic and sequences
Best for: Did X but not Y; streaks; sessions

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?
Interview tip: Talk while you work: clarify, name the pattern, build CTEs, test. Interviewers score your process as much as the final query, and a clear process recovers from small syntax slips.

Knowledge check

Loading quiz

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.

Open SQL Practice →SQL interview Q&A
Previous topic
GROUPING SETS, ROLLUP & CUBE for Multi-Level Subtotals
Next topic
Entity-Relationship Diagrams (ERD) & Conceptual Data Modeling