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.
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.
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
Keep one schema and validate counts
Pattern selection
16 solved interview exercises
Current big-tech coding patterns are shown first, followed by the core AI/data exercises.
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.
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);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.
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;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.
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;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.
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;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.
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;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.
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;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.
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;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.
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;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.
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;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.
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;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.
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;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.
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;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.
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
);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.
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;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.
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;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.
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;Review the deeper lessons
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.