Skip to main content
LearnMLAcademy
Advanced10 min read

SQL for AI/Data Interviews

Solve practical SQL interview questions using window functions and aggregations, with skill checklists, worked cases, and role-specific interview drills.

What you will master in this lesson
Intuitive core mechanisms & practical real-world intuition
Step-by-step mathematical breakdown & visual diagrams
Runnable Python implementation & practical trade-offs

SQL interviews test whether you can define the row grain, preserve it through joins, and reason about time, grouping, nulls, and duplicates. Correct syntax with the wrong grain still produces a wrong answer.

The expanded SQL set uses one small schema and emphasizes the patterns repeatedly reported for data interviews: joins, window functions, retention, experiments, funnels, rolling metrics, sessionization, nulls, and grain control.

UPDATED FOR 20267 current big-tech signals moved to the top

This is the expanded interview-preparation version

Current, research-driven questions are shown first so you can immediately see what changed. Each question keeps the detailed answer, example, likely follow-up, and weak-answer warning.

16
solved exercises

What you will be able to do

  • Define output grain before writing SQL
  • Use filters, joins, aggregates, CTEs, and CASE
  • Apply ROW_NUMBER, RANK, LAG, and rolling windows
  • Handle nulls and duplicates
  • Explain database-specific time syntax

Reason about a SQL query as transformations

Define grain before joins and windows

Define output grain
Filter eligible rows
Join at known keys
Aggregate / window
Rank / select
Validate counts
How to read it: Most SQL mistakes come from losing track of row grain, join multiplicity, time boundaries, or null behaviour.

Keep one schema and validate counts

Pattern selection

Pattern selection
NeedTypical SQL patternMain risk
Aggregate groupsGROUP BY + HAVINGFiltering at wrong stage
Keep unmatched rowsLEFT JOINWHERE clause turns it into inner join
Latest rowROW_NUMBER over partitionTies not deterministic
Compare adjacent eventsLAG / LEADWrong partition or order
Top N per groupRANK or ROW_NUMBERTie policy
Rolling metricWindow frameROWS versus time interval

16 solved interview exercises

Current big-tech coding patterns are shown first, followed by the core AI/data exercises.

RUNNABLE SQL / SQL EXAMPLE2026 SIGNAL

Retention queries and windowed user metrics recur in Google and Meta data-science interview reports.

10. Day-1 retention

Problem: For each signup date, calculate the percentage of users who generated any event on the calendar day after signup.

Reasoning: Keep one row per signed-up user, left join a deduplicated set of next-day active users, then aggregate at signup-date grain.

RUNNABLE SQL / SQL EXAMPLE
WITH next_day_active AS (
  SELECT DISTINCT u.user_id, CAST(u.signup_at AS DATE) AS signup_date
  FROM users u
  JOIN events e ON e.user_id = u.user_id
   AND CAST(e.event_time AS DATE) = CAST(u.signup_at AS DATE) + INTERVAL '1 day'
)
SELECT CAST(u.signup_at AS DATE) AS signup_date,
       COUNT(*) AS signups,
       AVG(CASE WHEN a.user_id IS NOT NULL THEN 1.0 ELSE 0.0 END) AS d1_retention
FROM users u
LEFT JOIN next_day_active a ON a.user_id = u.user_id
GROUP BY CAST(u.signup_at AS DATE);
Complexity: Join plus grouping; indexes on user_id and event time help.
Edge cases: Timezone, bot events, duplicate activity, and database-specific interval syntax.
Follow-up: Compute D7 retention using a cohort table.
RUNNABLE SQL / SQL EXAMPLE2026 SIGNAL

Recent Google Data Scientist reports specifically mention rolling-average and retention-style window questions.

11. Seven-day rolling daily active users

Problem: Return each date with the number of distinct users active in the previous seven calendar days.

Reasoning: A distinct-user rolling window is awkward in many SQL dialects. Build a date spine, join events in the seven-day interval, then count distinct users per date.

RUNNABLE SQL / SQL EXAMPLE
SELECT d.day, COUNT(DISTINCT e.user_id) AS active_users_7d
FROM calendar_days d
LEFT JOIN events e
  ON e.event_time >= d.day - INTERVAL '6 day'
 AND e.event_time < d.day + INTERVAL '1 day'
GROUP BY d.day
ORDER BY d.day;
Complexity: Range joins can be expensive; partition pruning or pre-aggregated user-day tables help at scale.
Edge cases: Timezone boundaries, sparse dates, duplicate events, and dialect-specific interval syntax.
Follow-up: How would you compute this efficiently over billions of events?
RUNNABLE SQL / SQL EXAMPLE2026 SIGNAL

Meta and Google data-science loops repeatedly emphasize A/B testing, metrics, and SQL together.

12. Experiment conversion by variant

Problem: Given experiment_assignments(user_id, variant, assigned_at), calculate purchase conversion per variant after assignment.

Reasoning: Preserve one assignment row per user, then detect whether any qualifying purchase occurred after assignment. Aggregate at variant grain.

RUNNABLE SQL / SQL EXAMPLE
WITH converted AS (
  SELECT a.user_id, a.variant,
         MAX(CASE WHEN o.order_time >= a.assigned_at THEN 1 ELSE 0 END) AS converted
  FROM experiment_assignments a
  LEFT JOIN orders o ON o.user_id = a.user_id
  GROUP BY a.user_id, a.variant
)
SELECT variant, COUNT(*) AS users, AVG(1.0 * converted) AS conversion_rate
FROM converted
GROUP BY variant;
Complexity: Join plus per-user aggregation.
Edge cases: Users assigned twice, pre-experiment orders, delayed conversion windows, sample-ratio mismatch, and exposure versus assignment.
Follow-up: How would you test whether the conversion difference is statistically meaningful?
RUNNABLE SQL / SQL EXAMPLE2026 SIGNAL

Sessionization is a high-value window-function pattern for product/data interviews.

13. Sessionize events with a 30-minute inactivity gap

Problem: Assign a session number to each user's events when a new session starts after more than 30 minutes of inactivity.

Reasoning: Use LAG to compare each event with the previous one, flag new sessions, then cumulatively sum the flags.

RUNNABLE SQL / SQL EXAMPLE
WITH gaps AS (
  SELECT e.*,
         LAG(event_time) OVER (PARTITION BY user_id ORDER BY event_time, event_id) AS prev_time
  FROM events e
), flags AS (
  SELECT gaps.*,
         CASE WHEN prev_time IS NULL OR event_time > prev_time + INTERVAL '30 minute' THEN 1 ELSE 0 END AS new_session
  FROM gaps
)
SELECT flags.*,
       SUM(new_session) OVER (PARTITION BY user_id ORDER BY event_time, event_id) AS session_id
FROM flags;
Complexity: Dominated by per-user event sorting.
Edge cases: Exactly 30 minutes, late-arriving events, timezone, and simultaneous timestamps.
Follow-up: Return one row per session with duration and event count.
RUNNABLE SQL / SQL EXAMPLE2026 SIGNAL

Product-metric SQL at Google and Meta frequently combines aggregation with window functions.

14. Month-over-month active-user growth

Problem: Calculate monthly active users and percentage growth from the previous month.

Reasoning: Aggregate distinct active users per month, then use LAG on the monthly result.

RUNNABLE SQL / SQL EXAMPLE
WITH monthly AS (
  SELECT DATE_TRUNC('month', event_time) AS month,
         COUNT(DISTINCT user_id) AS mau
  FROM events
  GROUP BY DATE_TRUNC('month', event_time)
), with_prev AS (
  SELECT month, mau, LAG(mau) OVER (ORDER BY month) AS prev_mau
  FROM monthly
)
SELECT month, mau,
       CASE WHEN prev_mau > 0 THEN 100.0 * (mau - prev_mau) / prev_mau END AS growth_pct
FROM with_prev
ORDER BY month;
Complexity: Distinct aggregation plus ordering over monthly rows.
Edge cases: Missing months need a date spine; define user timezone and activity event.
Follow-up: Segment growth by country without changing the denominator accidentally.
RUNNABLE SQL / SQL EXAMPLE2026 SIGNAL

Consecutive-period problems are common SQL interview tests because they expose grain and window-function skill.

15. Consecutive active-day streak

Problem: Find each user's longest streak of consecutive active calendar days.

Reasoning: Deduplicate to user-day grain, assign row numbers, and use the date-minus-row-number trick to group consecutive dates.

RUNNABLE SQL / SQL EXAMPLE
WITH days AS (
  SELECT DISTINCT user_id, CAST(event_time AS DATE) AS day
  FROM events
), numbered AS (
  SELECT user_id, day, ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY day) AS rn
  FROM days
), islands AS (
  SELECT user_id, day, day - rn * INTERVAL '1 day' AS grp
  FROM numbered
), streaks AS (
  SELECT user_id, grp, COUNT(*) AS streak_days
  FROM islands
  GROUP BY user_id, grp
)
SELECT user_id, MAX(streak_days) AS longest_streak
FROM streaks
GROUP BY user_id;
Complexity: Deduplication plus per-user sort.
Edge cases: Timezone, duplicate events, missing calendar days, and dialect-specific date arithmetic.
Follow-up: Return the start and end date of each user's longest streak.
RUNNABLE SQL / SQL EXAMPLE2026 SIGNAL

Segment-level model metrics connect SQL skill directly to ML evaluation and production monitoring.

16. Compare model performance by segment

Problem: For each user segment, calculate labelled count, accuracy, precision, recall, and average score.

Reasoning: Join predictions to users once, use conditional aggregation, and protect zero denominators.

RUNNABLE SQL / SQL EXAMPLE
SELECT u.segment,
       COUNT(*) AS labelled,
       AVG(CASE WHEN p.predicted_label = p.actual_label THEN 1.0 ELSE 0.0 END) AS accuracy,
       SUM(CASE WHEN p.predicted_label = 1 AND p.actual_label = 1 THEN 1 ELSE 0 END) * 1.0 /
         NULLIF(SUM(CASE WHEN p.predicted_label = 1 THEN 1 ELSE 0 END), 0) AS precision,
       SUM(CASE WHEN p.predicted_label = 1 AND p.actual_label = 1 THEN 1 ELSE 0 END) * 1.0 /
         NULLIF(SUM(CASE WHEN p.actual_label = 1 THEN 1 ELSE 0 END), 0) AS recall,
       AVG(p.score) AS avg_score
FROM predictions p
JOIN users u ON u.user_id = p.user_id
WHERE p.actual_label IS NOT NULL
GROUP BY u.segment;
Complexity: Join and grouped scan.
Edge cases: Delayed labels, segment drift, duplicated user rows, and undefined precision/recall when denominators are zero.
Follow-up: Add confidence intervals or minimum sample-size rules before alerting on a segment.
RUNNABLE SQL / SQL EXAMPLE

1. Latest event per user

Problem: Return one latest event for each user with deterministic tie-breaking.

Reasoning: Rank inside each user by event time and then event ID, then keep row 1.

RUNNABLE SQL / SQL EXAMPLE
WITH ranked AS (
  SELECT e.*,
         ROW_NUMBER() OVER (
           PARTITION BY user_id
           ORDER BY event_time DESC, event_id DESC
         ) AS rn
  FROM events AS e
)
SELECT user_id, event_id, event_time, event_name
FROM ranked
WHERE rn = 1;
Complexity: Typically O(n log n) for partitioned sorting; indexes may reduce work.
Edge cases: Equal timestamps, users without events, and database timestamp precision.
Follow-up: Include every user, returning null when no event exists.
RUNNABLE SQL / SQL EXAMPLE

2. Immediate next event

Problem: For every event, show the next event name and time for the same user.

Reasoning: LEAD looks forward within a user-ordered partition without a self-join.

RUNNABLE SQL / SQL EXAMPLE
SELECT user_id, event_id, event_name, event_time,
       LEAD(event_name) OVER (
         PARTITION BY user_id ORDER BY event_time, event_id
       ) AS next_event,
       LEAD(event_time) OVER (
         PARTITION BY user_id ORDER BY event_time, event_id
       ) AS next_event_time
FROM events;
Complexity: Dominated by sorting each user's events.
Edge cases: The last event has null next values; ties require a stable secondary key.
Follow-up: Calculate time until the next purchase event only.
RUNNABLE SQL / SQL EXAMPLE

3. Top product per category

Problem: Find the highest-revenue product in each category and keep ties.

Reasoning: Aggregate revenue first, then rank products within each category using RANK.

RUNNABLE SQL / SQL EXAMPLE
WITH revenue AS (
  SELECT category, product_id, SUM(amount) AS total_revenue
  FROM orders
  GROUP BY category, product_id
), ranked AS (
  SELECT revenue.*,
         RANK() OVER (PARTITION BY category ORDER BY total_revenue DESC) AS revenue_rank
  FROM revenue
)
SELECT category, product_id, total_revenue
FROM ranked
WHERE revenue_rank = 1;
Complexity: Aggregation plus per-category ranking; physical cost depends on indexes and cardinality.
Edge cases: Ties return multiple products; cancelled orders and currency need policy.
Follow-up: Return exactly one product with a deterministic tie-breaker.
RUNNABLE SQL / SQL EXAMPLE

4. Remove duplicate events

Problem: Identify all but the earliest record for each logical event key.

Reasoning: ROW_NUMBER marks duplicates while preserving the first by ingestion order.

RUNNABLE SQL / SQL EXAMPLE
WITH marked AS (
  SELECT e.*,
         ROW_NUMBER() OVER (
           PARTITION BY event_id ORDER BY event_time, user_id
         ) AS duplicate_number
  FROM events AS e
)
SELECT *
FROM marked
WHERE duplicate_number > 1;
Complexity: Sorting within duplicate keys; often O(n log n).
Edge cases: A truly unique event_id would never duplicate; production tables may need a separate ingestion timestamp.
Follow-up: How would you delete safely without losing audit evidence?
RUNNABLE SQL / SQL EXAMPLE

5. Seven-day activity count

Problem: Count each user's events by day for a rolling seven-observed-day window.

Reasoning: Aggregate to one row per user-day first, then window over daily rows. A ROWS frame assumes missing days are intentionally absent.

RUNNABLE SQL / SQL EXAMPLE
WITH daily AS (
  SELECT user_id, CAST(event_time AS DATE) AS event_date,
         COUNT(*) AS events_that_day
  FROM events
  GROUP BY user_id, CAST(event_time AS DATE)
)
SELECT user_id, event_date,
       SUM(events_that_day) OVER (
         PARTITION BY user_id ORDER BY event_date
         ROWS BETWEEN 6 PRECEDING AND CURRENT ROW
       ) AS activity_last_7_observed_days
FROM daily;
Complexity: Group then sort per user.
Edge cases: This is seven observed days, not always seven calendar days; interval frames vary by database.
Follow-up: Generate a date spine for true calendar-day windows.
RUNNABLE SQL / SQL EXAMPLE

6. Users with no purchases

Problem: Return users that have no matching order.

Reasoning: Use NOT EXISTS to express the anti-join without duplicate concerns.

RUNNABLE SQL / SQL EXAMPLE
SELECT u.user_id, u.segment
FROM users AS u
WHERE NOT EXISTS (
  SELECT 1
  FROM orders AS o
  WHERE o.user_id = u.user_id
);
Complexity: With an index on orders.user_id, lookups are efficient; otherwise the engine may scan.
Edge cases: Decide whether cancelled or zero-value orders count as purchases.
Follow-up: Return users with no purchase in the last 30 days.
RUNNABLE SQL / SQL EXAMPLE

7. False-positive count by segment

Problem: Count negative actuals predicted positive for each user segment.

Reasoning: Join each prediction to its user, then conditionally aggregate at segment grain.

RUNNABLE SQL / SQL EXAMPLE
SELECT u.segment,
       SUM(CASE WHEN p.predicted_label = 1 AND p.actual_label = 0 THEN 1 ELSE 0 END) AS false_positives,
       COUNT(*) AS labelled_predictions
FROM predictions AS p
JOIN users AS u ON u.user_id = p.user_id
WHERE p.actual_label IS NOT NULL
GROUP BY u.segment;
Complexity: Join plus grouping; index the join key for scale.
Edge cases: Delayed labels are excluded; repeated user rows would multiply predictions.
Follow-up: Calculate false-positive rate with a safe zero denominator.
RUNNABLE SQL / SQL EXAMPLE

8. Rolling model score

Problem: Calculate a three-prediction moving average per user.

Reasoning: A ROWS window maintains the current and two previous predictions in time order.

RUNNABLE SQL / SQL EXAMPLE
SELECT user_id, predicted_at, score,
       AVG(score) OVER (
         PARTITION BY user_id
         ORDER BY predicted_at, prediction_id
         ROWS BETWEEN 2 PRECEDING AND CURRENT ROW
       ) AS avg_last_3_scores
FROM predictions;
Complexity: Per-user sorting dominates.
Edge cases: Early rows average fewer than three values; null scores and timestamp ties need policy.
Follow-up: Use a real seven-day time interval for the window.
RUNNABLE SQL / SQL EXAMPLE

9. Conversion funnel

Problem: Count users who viewed, added to cart, and purchased in that order.

Reasoning: Find each user's first view, then the first valid cart after that view, and finally the first valid purchase after that cart. Count non-null timestamps only after each earlier stage has been established.

RUNNABLE SQL / SQL EXAMPLE
WITH first_view AS (
  SELECT user_id, MIN(event_time) AS viewed_at
  FROM events
  WHERE event_name = 'view'
  GROUP BY user_id
),
first_cart_after_view AS (
  SELECT v.user_id, v.viewed_at,
         MIN(e.event_time) AS cart_at
  FROM first_view AS v
  LEFT JOIN events AS e
    ON e.user_id = v.user_id
   AND e.event_name = 'add_to_cart'
   AND e.event_time > v.viewed_at
  GROUP BY v.user_id, v.viewed_at
),
first_purchase_after_cart AS (
  SELECT c.user_id, c.viewed_at, c.cart_at,
         MIN(e.event_time) AS purchased_at
  FROM first_cart_after_view AS c
  LEFT JOIN events AS e
    ON e.user_id = c.user_id
   AND e.event_name = 'purchase'
   AND c.cart_at IS NOT NULL
   AND e.event_time > c.cart_at
  GROUP BY c.user_id, c.viewed_at, c.cart_at
)
SELECT COUNT(*) AS users_viewed,
       SUM(CASE WHEN cart_at IS NOT NULL THEN 1 ELSE 0 END) AS users_reached_cart,
       SUM(CASE WHEN purchased_at IS NOT NULL THEN 1 ELSE 0 END) AS users_purchased
FROM first_purchase_after_cart;
Complexity: Three grouped passes over the relevant event stages; an index on user_id, event_name, and event_time can reduce join work.
Edge cases: A production funnel may also require session boundaries, a maximum allowed time between stages, and deterministic ordering for events with identical timestamps.
Follow-up: Add a 24-hour session boundary while preserving the same ordered-stage logic.

Use these links when an interview question exposes a gap. The interview guide focuses on explanation and decision-making; the linked lesson teaches the full concept.

Keep the answer honest: role boundaries, interview processes, and project outcomes vary. Never invent experience, impact, salary, or certainty to make an answer sound stronger.

Summary / Key Takeaways

  • Define the requested output grain before choosing SQL clauses.
  • WHERE filters rows before grouping; HAVING filters groups after aggregation.
  • Join keys and cardinality determine whether rows are preserved or multiplied.
  • Window functions calculate across related rows without collapsing their grain.
  • ROW_NUMBER and RANK encode different tie behaviour and need deterministic ordering.
  • Time windows, nulls, delayed labels, and duplicate events require explicit policies.
  • A strong SQL answer validates row counts, edge cases, portability, and likely index needs.

Apply this concept in a real hands-on project

You have studied the idea. Now use it in working Python code, see the calculation and output, and explain what changed. Each project includes step-by-step instructions, full source and tests.

Practice challenge: predict an outcome first, run the code, and explain the difference.

Track Your Progress0% curriculum done

Finished "SQL for AI/Data Interviews"?

Mark this lesson as completed to update your progress bar and track your milestones across the full curriculum.

Overall Progress0 / 167 lessons

Was this tutorial helpful?

Your feedback helps us continuously refine and improve our open-access tutorials.

Knowledge Check

Progress: 0/5

Test your active recall. Choose one answer for each question, then check it to reveal the step-by-step reasoning.

Question 1 of 5practical selection
Which function returns one latest row per user when ties are deterministically ordered?
Question 2 of 5interpretation
Why aggregate revenue before ranking products within categories?
Question 3 of 5conceptual
What does the last row in a LEAD window return for next_event?
Question 4 of 5debugging/diagnostic
Why can a LEFT JOIN accidentally become an inner join?
Question 5 of 5interpretation
A ROWS BETWEEN 6 PRECEDING frame over daily rows means what?

Knowledge Check Review & Explanations

Review the questions, verified correct answers, and conceptual explanations for this lesson.

1Which function returns one latest row per user when ties are deterministically ordered?▼

Correct Answer: ROW_NUMBER

ROW_NUMBER partitions by user and ranks rows according to the stated order so rn=1 selects one.

2Why aggregate revenue before ranking products within categories?▼

Correct Answer: The desired grain is one product-category revenue row

Ranking raw orders would rank transactions rather than products by total revenue.

3What does the last row in a LEAD window return for next_event?▼

Correct Answer: NULL

No later row exists in that partition, so LEAD returns null unless a default is supplied.

4Why can a LEFT JOIN accidentally become an inner join?▼

Correct Answer: A WHERE filter rejects null rows from the right table

Filtering a right-table column in WHERE often removes unmatched rows whose right-side values are null.

5A ROWS BETWEEN 6 PRECEDING frame over daily rows means what?▼

Correct Answer: Seven observed rows including current

ROWS counts rows, so missing calendar dates make it different from a true seven-day interval.

Keep moving through the path

Continue Learning

Free Download: SQL for Data & AI Interviews

Solved SQL interview problems for data and AI roles with sample tables, step-by-step query logic, window functions, joins, analytics patterns and expected outputs. Enter your email to download it instantly.

Next