Company-Wise SQL Interview Questions & Solutions (Part 1: FAANG & Enterprise Giants)
This article is available in English. Browse translated guides in the language menu.
Technical screening rounds at tier-1 enterprise organizations—Meta, Amazon, Google, Microsoft, Apple, and Netflix—do not test memorized syntax or toy schemas. Staff interviewers look for query plan awareness, defensive handling of real-world edge cases (NULLs, timestamp ties, missing dimensions), and scalable analytical mechanics.
Whether you are targeting Data Engineering, Business Intelligence, Backend Architecture, or Product Data Science, this guide breaks down 36 high-frequency, battle-tested SQL problems across the 6 major tech leaders. You can also practice similar problems with automated testing in our Top 50 SQL Interview Challenges or write and run queries directly in our zero-setup SQL Lab.
Every question features:
- Business Problem & Context
- Schema & Data Types
- Production-Ready SQL Solution (PostgreSQL / ANSI standard)
- Execution Mechanics & Architectural Trade-offs
- Common Traps & Anti-patterns
- Senior Follow-up / Scalability Consideration
Navigation & Enterprise Company Breakdown
- 1. Meta (Questions 1 to 6)
- 2. Amazon (Questions 7 to 12)
- 3. Google (Questions 13 to 18)
- 4. Microsoft (Questions 19 to 24)
- 5. Apple (Questions 25 to 30)
- 6. Netflix (Questions 31 to 36)
- Cross-Reference: Part 2 (Marketplaces, Fintech & Unicorns)
1. Meta (Facebook, Instagram, WhatsApp)
Meta focuses aggressively on user engagement loops, social graph interactions, attribution windows, and feed/ad conversion telemetry.
Question 1: Daily Active Users (DAU) to Monthly Active Users (MAU) Ratio (Stickiness)
- Company: Meta
- Difficulty: Medium
- Core Concepts: Self-Join on Date Intervals,
COUNT(DISTINCT), Rolling Windows, Stickiness Metric
Scenario & Schema
Meta product analytics teams measure product engagement using the “L28” or DAU/MAU stickiness ratio. Given an activity log, calculate the DAU/MAU ratio for each date in July 2026.
user_actions(user_id INT, action_date DATE, action_type VARCHAR(32))
Solution
WITH daily_active AS (
SELECT
action_date,
COUNT(DISTINCT user_id) AS dau
FROM user_actions
WHERE action_date BETWEEN '2026-06-01' AND '2026-07-31'
GROUP BY action_date
),
rolling_active AS (
SELECT
d.action_date,
d.dau,
COUNT(DISTINCT u.user_id) AS mau
FROM daily_active d
JOIN user_actions u
ON u.action_date BETWEEN d.action_date - INTERVAL '29 days' AND d.action_date
WHERE d.action_date BETWEEN '2026-07-01' AND '2026-07-31'
GROUP BY d.action_date, d.dau
)
SELECT
action_date,
dau,
mau,
ROUND((dau::NUMERIC / NULLIF(mau, 0)) * 100, 2) AS stickiness_percent
FROM rolling_active
ORDER BY action_date ASC;
Why It Works & Architectural Mechanics
- A naive
COUNT(DISTINCT)over a window function (OVER (ORDER BY action_date ROWS BETWEEN 29 PRECEDING...)) is disallowed in standard SQL because distinct aggregations across sliding window frames cannot be incrementally collapsed without maintaining full hash sets. - Joining the aggregated calendar day
dto the raw table within a bounded date range creates a deterministic 30-day window (INTERVAL '29 days'). NULLIF(mau, 0)protects against division-by-zero crashes on brand-new regional rollouts.
Common Traps
- Counting rows instead of distinct users (
COUNT(*)vsCOUNT(DISTINCT user_id)). A user with 40 interactions in one day must count as 1 DAU. - Filtering out June in the base CTE: calculating July 1st MAU requires historical access to June 2nd through June 30th.
Follow-up / Production Scale
- On a dataset with 3 billion daily events, self-joining 30 days generates 90 billion row comparisons. In production pipelines (Presto/Spark/Trino), replace this query with HyperLogLog sketch aggregates (
approx_distinctorHLL_UNION).
Question 2: First-to-Second Ad Click Attribution Lag
- Company: Meta
- Difficulty: Medium
- Core Concepts: Window Functions (
LEAD), Epoch Timestamp Diff, Filtering Consecutive Events
Scenario & Schema
Ad engineers want to identify users exhibiting click-burst behaviour. Find the time delta in seconds between a user’s first ad click and their second ad click. Filter for users who clicked at least twice.
ad_clicks(click_id BIGINT, user_id BIGINT, ad_id BIGINT, clicked_at TIMESTAMP)
Solution
WITH ranked_clicks AS (
SELECT
user_id,
clicked_at,
ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY clicked_at ASC, click_id ASC) AS click_seq
FROM ad_clicks
)
SELECT
c1.user_id,
c1.clicked_at AS first_click,
c2.clicked_at AS second_click,
EXTRACT(EPOCH FROM (c2.clicked_at - c1.clicked_at))::INT AS lag_seconds
FROM ranked_clicks c1
JOIN ranked_clicks c2
ON c1.user_id = c2.user_id
AND c1.click_seq = 1
AND c2.click_seq = 2
ORDER BY lag_seconds ASC;
Why It Works & Architectural Mechanics
- Partitioning by
user_idand indexing byclicked_at ASCisolates each user’s event chronology. Addingclick_id ASCbreaks millisecond ties deterministically. - Self-joining on
click_seq = 1andclick_seq = 2is dramatically more index-friendly than running nested correlated subqueries.
Common Traps
- Using
DENSE_RANK()instead ofROW_NUMBER(): if two clicks land at the identical millisecond,DENSE_RANKassigns1to both, breaking equality joins on sequence numbers.
Follow-up / Production Scale
- Can this be done in a single scan? Yes, using
LEAD(clicked_at, 1) OVER (PARTITION BY user_id ORDER BY clicked_at ASC)combined with aQUALIFYclause (Snowflake/BigQuery) or an outer CTE filterWHERE click_seq = 1 AND next_clicked_at IS NOT NULL.
Question 3: Mutual Friends Count Between Direct Connections
- Company: Meta
- Difficulty: Hard
- Core Concepts: Undirected Graph Representation, Self-Join, Group Intersection
Scenario & Schema
Given an undirected friendship table, find the number of mutual friends for all pairs of directly connected friends.
friendships(user1_id INT, user2_id INT)whereuser1_id < user2_id.
Solution
WITH bidirectional_friends AS (
SELECT user1_id AS user_id, user2_id AS friend_id FROM friendships
UNION ALL
SELECT user2_id AS user_id, user1_id AS friend_id FROM friendships
)
SELECT
f.user1_id,
f.user2_id,
COUNT(b2.friend_id) AS mutual_friends_count
FROM friendships f
JOIN bidirectional_friends b1
ON f.user1_id = b1.user_id
JOIN bidirectional_friends b2
ON f.user2_id = b2.user_id
AND b1.friend_id = b2.friend_id
GROUP BY f.user1_id, f.user2_id
ORDER BY mutual_friends_count DESC, f.user1_id, f.user2_id;
Why It Works & Architectural Mechanics
- Social connections are non-directional. Transforming the triangle via
UNION ALLcreates an indexed two-way adjacency list. - The join between
b1andb2onb1.friend_id = b2.friend_idcalculates the exact set intersection: $(Adj(u_1) \cap Adj(u_2))$.
Common Traps
- Using
UNIONinstead ofUNION ALL:UNIONforces a costly duplicate sort across the entire table. Sinceuser1_id < user2_idis guaranteed, duplicate pairs do not exist across the two branches.
Follow-up / Production Scale
- In production graph storage (TAO at Meta), graph intersection is executed via distributed bitmap index AND-operations rather than SQL joins.
Question 4: De-duplicate User Posts Retaining Only the Earliest Record
- Company: Meta
- Difficulty: Medium
- Core Concepts: Window Functions, Data Cleaning, CTE Mutation (
DELETE ... RETURNING)
Scenario & Schema
A network retry bug created duplicated posts with identical user_id, content_hash, and identical minute timestamps. Retain only the record with the minimum post_id.
posts(post_id BIGINT, user_id BIGINT, content_hash VARCHAR(64), created_at TIMESTAMP)
Solution
WITH ranked_duplicates AS (
SELECT
post_id,
ROW_NUMBER() OVER (
PARTITION BY user_id, content_hash, DATE_TRUNC('minute', created_at)
ORDER BY post_id ASC
) AS row_num
FROM posts
)
DELETE FROM posts
WHERE post_id IN (
SELECT post_id
FROM ranked_duplicates
WHERE row_num > 1
);
Why It Works & Architectural Mechanics
ROW_NUMBER() = 1flags the canonical row (the lowestpost_id). Rows withrow_num > 1are safe deletion candidates.- In PostgreSQL, partitioning over composite keys utilizes a composite index
(user_id, content_hash, created_at)to perform a fast B-Tree scan without reading heap tables twice.
Common Traps
- Using
MIN(post_id)withGROUP BYinside aDELETE WHERE post_id NOT IN (...): if the table has millions of rows,NOT INcreates a catastrophic materialized list that stalls WAL logs.
Question 5: Multi-Stage Story Funnel Drop-Off Rate
- Company: Meta
- Difficulty: Hard
- Core Concepts: Conditional Aggregation, Chronological Funnel, Step-Wise Drop-off
Scenario & Schema
Track the 3-stage Instagram Story funnel: view_story -> react_story -> send_dm. An event is only valid if it occurs chronologically after the previous stage within a 1-hour window. Calculate drop-off percentages between stages.
story_events(event_id BIGINT, user_id BIGINT, story_id BIGINT, stage VARCHAR(32), event_time TIMESTAMP)
Solution
WITH user_story_stages AS (
SELECT
user_id,
story_id,
MIN(CASE WHEN stage = 'view_story' THEN event_time END) AS view_time,
MIN(CASE WHEN stage = 'react_story' THEN event_time END) AS react_time,
MIN(CASE WHEN stage = 'send_dm' THEN event_time END) AS dm_time
FROM story_events
GROUP BY user_id, story_id
),
valid_funnel_completions AS (
SELECT
user_id,
story_id,
view_time,
CASE
WHEN react_time > view_time AND react_time <= view_time + INTERVAL '1 hour'
THEN react_time
END AS valid_react_time,
CASE
WHEN react_time > view_time AND dm_time > react_time AND dm_time <= view_time + INTERVAL '1 hour'
THEN dm_time
END AS valid_dm_time
FROM user_story_stages
WHERE view_time IS NOT NULL
)
SELECT
COUNT(view_time) AS total_views,
COUNT(valid_react_time) AS total_reactions,
COUNT(valid_dm_time) AS total_dms,
ROUND((1.0 - (COUNT(valid_react_time)::NUMERIC / NULLIF(COUNT(view_time), 0))) * 100, 2) AS view_to_react_dropoff_pct,
ROUND((1.0 - (COUNT(valid_dm_time)::NUMERIC / NULLIF(COUNT(valid_react_time), 0))) * 100, 2) AS react_to_dm_dropoff_pct
FROM valid_funnel_completions;
Why It Works & Architectural Mechanics
- Aggregating via
MIN(CASE WHEN ...)pivots the event stream per(user_id, story_id)in a single scan. - Explicit timestamp inequalities enforce strict sequence validation without expensive multi-way self-joins.
Question 6: N-Day Retention Cohort Matrix
- Company: Meta
- Difficulty: Hard
- Core Concepts: Cohort Analysis, Date Arithmetic, Pivoted Retention Rates
Scenario & Schema
Calculate Day 1, Day 7, and Day 30 retention rates for cohorts of users grouped by their signup date in January 2026.
users(user_id INT, signup_date DATE)activity(user_id INT, login_date DATE)
Solution
WITH cohort_sizes AS (
SELECT
signup_date,
COUNT(DISTINCT user_id) AS cohort_users
FROM users
WHERE signup_date BETWEEN '2026-01-01' AND '2026-01-31'
GROUP BY signup_date
),
activity_deltas AS (
SELECT
u.signup_date,
u.user_id,
a.login_date - u.signup_date AS day_diff
FROM users u
JOIN activity a ON u.user_id = a.user_id
WHERE u.signup_date BETWEEN '2026-01-01' AND '2026-01-31'
)
SELECT
c.signup_date,
c.cohort_users,
ROUND(COUNT(DISTINCT CASE WHEN a.day_diff = 1 THEN a.user_id END)::NUMERIC / c.cohort_users * 100, 2) AS day_1_retention_pct,
ROUND(COUNT(DISTINCT CASE WHEN a.day_diff = 7 THEN a.user_id END)::NUMERIC / c.cohort_users * 100, 2) AS day_7_retention_pct,
ROUND(COUNT(DISTINCT CASE WHEN a.day_diff = 30 THEN a.user_id END)::NUMERIC / c.cohort_users * 100, 2) AS day_30_retention_pct
FROM cohort_sizes c
LEFT JOIN activity_deltas a ON c.signup_date = a.signup_date
GROUP BY c.signup_date, c.cohort_users
ORDER BY c.signup_date ASC;
Why It Works & Architectural Mechanics
- Computes
day_diffonce per user-login pair. - Conditional
COUNT(DISTINCT CASE WHEN ...)acts as an inline filter, eliminating the need to construct 3 separate subqueries for Days 1, 7, and 30.
2. Amazon (Retail, AWS, Fulfillment)
Amazon SQL interviews test inventory reconciliation, e-commerce basket analysis, moving supply-chain metrics, and handling sparse transactional facts.
Question 7: Month-over-Month Category Revenue Growth
- Company: Amazon
- Difficulty: Medium
- Core Concepts: Window Functions (
LAG), Date Truncation, Relative Delta
Scenario & Schema
Calculate the monthly revenue and Month-over-Month (MoM) percentage revenue growth for each product category during 2026.
orders(order_id BIGINT, order_date DATE, category_id INT, amount NUMERIC(12,2))
Solution
WITH monthly_category_revenue AS (
SELECT
category_id,
DATE_TRUNC('month', order_date)::DATE AS sales_month,
SUM(amount) AS current_revenue
FROM orders
WHERE order_date >= '2026-01-01' AND order_date < '2027-01-01'
GROUP BY category_id, DATE_TRUNC('month', order_date)
)
SELECT
category_id,
sales_month,
current_revenue,
LAG(current_revenue, 1) OVER (
PARTITION BY category_id
ORDER BY sales_month ASC
) AS prev_month_revenue,
ROUND(
(current_revenue - LAG(current_revenue, 1) OVER (PARTITION BY category_id ORDER BY sales_month ASC))
/ NULLIF(LAG(current_revenue, 1) OVER (PARTITION BY category_id ORDER BY sales_month ASC), 0) * 100,
2
) AS mom_growth_pct
FROM monthly_category_revenue
ORDER BY category_id, sales_month ASC;
Why It Works & Architectural Mechanics
DATE_TRUNC('month', order_date)standardizes irregular order dates into a unified monthly bucket.LAG(..., 1)reads the immediately preceding month within the samecategory_id.- The
NULLIFsafeguard prevents runtime errors whenprev_month_revenueis zero orNULL(such as the first month of product launch).
Question 8: Identifying Inactive Catalog Products (Left Anti-Join vs NOT EXISTS)
- Company: Amazon
- Difficulty: Medium
- Core Concepts: Anti-Joins, Optimizer NULL Semantics, Execution Plans
Scenario & Schema
Find all product items in warehouse US-EAST-1 that have had zero customer purchases in the last 180 days.
products(product_id INT, warehouse_id VARCHAR(16), product_name VARCHAR(255))order_items(order_id BIGINT, product_id INT, purchase_date DATE)
Solution
SELECT
p.product_id,
p.product_name
FROM products p
WHERE p.warehouse_id = 'US-EAST-1'
AND NOT EXISTS (
SELECT 1
FROM order_items oi
WHERE oi.product_id = p.product_id
AND oi.purchase_date >= CURRENT_DATE - INTERVAL '180 days'
);
Architectural Trade-offs: NOT EXISTS vs NOT IN vs LEFT JOIN / IS NULL
- Why NOT EXISTS is preferred: If
order_items.product_idcontains a singleNULL, standard ANSINOT IN (SELECT product_id ...)evaluates toUNKNOWNfor all rows, returning an empty result set! NOT EXISTSis safe against NULL values and allows the query planner to employ a Null-Aware Anti-Hash Join or early-abort correlated Index Scan.
Question 9: 3-Day Rolling Average Inventory Replenishment
- Company: Amazon
- Difficulty: Medium
- Core Concepts: Moving Averages, Window Frame Clauses (
ROWSvsRANGE), Supply Chain Telemetry
Scenario & Schema
To trigger automated purchase orders, compute a 3-day moving average of stock withdrawals for each SKU.
stock_events(event_id BIGINT, sku_id VARCHAR(32), event_date DATE, quantity_withdrawn INT)
Solution
WITH daily_withdrawals AS (
SELECT
sku_id,
event_date,
SUM(quantity_withdrawn) AS daily_qty
FROM stock_events
GROUP BY sku_id, event_date
)
SELECT
sku_id,
event_date,
daily_qty,
ROUND(
AVG(daily_qty) OVER (
PARTITION BY sku_id
ORDER BY event_date ASC
ROWS BETWEEN 2 PRECEDING AND CURRENT ROW
),
2
) AS rolling_3day_avg_qty
FROM daily_withdrawals
ORDER BY sku_id, event_date ASC;
Execution Mechanics
ROWS BETWEEN 2 PRECEDING AND CURRENT ROWexplicitly defines a 3-row moving window frame.RANGE BETWEEN INTERVAL '2 days' PRECEDING AND CURRENT ROWshould be chosen if dates are sparse and non-contiguous.
Question 10: Exclusive Category Shoppers (A and B but NOT C)
- Company: Amazon
- Difficulty: Hard
- Core Concepts: Set Division, Relational Division, Group-Wise Boolean Aggregation
Scenario & Schema
Find customers who bought items from Books (Category 1) AND Electronics (Category 2), but have NEVER purchased anything from Clothing (Category 3).
orders(customer_id INT, category_id INT)
Solution
SELECT
customer_id
FROM orders
GROUP BY customer_id
HAVING COUNT(DISTINCT CASE WHEN category_id = 1 THEN 1 END) > 0
AND COUNT(DISTINCT CASE WHEN category_id = 2 THEN 1 END) > 0
AND COUNT(CASE WHEN category_id = 3 THEN 1 END) = 0;
Why It Works & Architectural Mechanics
- A single pass through the
orderstable usingHAVINGfilters out non-qualifying customers with minimal memory footprint ($O(N)$ vs multiple joins $O(N \log N)$). - Avoids expensive triple-nested subqueries (
WHERE customer_id IN (...) AND customer_id IN (...) AND customer_id NOT IN (...)).
Question 11: P90 and P95 Fulfillment Center Latency
- Company: Amazon
- Difficulty: Hard
- Core Concepts: Continuous vs Discrete Percentiles (
PERCENTILE_CONT), SLA Diagnostics
Scenario & Schema
AWS Logistics monitors package processing times from created_at to dispatched_at (in minutes). Calculate the 50th (median), 90th, and 95th percentile fulfillment latency per warehouse facility.
shipments(shipment_id BIGINT, facility_id VARCHAR(16), created_at TIMESTAMP, dispatched_at TIMESTAMP)
Solution
WITH latency_calc AS (
SELECT
facility_id,
EXTRACT(EPOCH FROM (dispatched_at - created_at)) / 60.0 AS duration_minutes
FROM shipments
WHERE dispatched_at IS NOT NULL
AND dispatched_at >= created_at
)
SELECT
facility_id,
ROUND(PERCENTILE_CONT(0.50) WITHIN GROUP (ORDER BY duration_minutes)::NUMERIC, 2) AS p50_minutes,
ROUND(PERCENTILE_CONT(0.90) WITHIN GROUP (ORDER BY duration_minutes)::NUMERIC, 2) AS p90_minutes,
ROUND(PERCENTILE_CONT(0.95) WITHIN GROUP (ORDER BY duration_minutes)::NUMERIC, 2) AS p95_minutes
FROM latency_calc
GROUP BY facility_id
ORDER BY p95_minutes DESC;
Why It Works & Architectural Mechanics
PERCENTILE_CONTuses linear interpolation between data points to compute exact mathematical percentiles.- Pre-filtering
dispatched_at >= created_atprotects against clock skew errors in warehouse scanners.
Question 12: Previous and Next Price Volatility Discrepancies
- Company: Amazon
- Difficulty: Medium
- Core Concepts:
LAG,LEAD, Bounded Window Sorting, Audit Trails
Scenario & Schema
Detect vendor price anomalies where a product price changes by more than 30% compared to both its prior price and its immediately following price.
price_history(product_id INT, effective_date DATE, unit_price NUMERIC(10,2))
Solution
WITH price_context AS (
SELECT
product_id,
effective_date,
unit_price,
LAG(unit_price, 1) OVER (PARTITION BY product_id ORDER BY effective_date ASC) AS prev_price,
LEAD(unit_price, 1) OVER (PARTITION BY product_id ORDER BY effective_date ASC) AS next_price
FROM price_history
)
SELECT
product_id,
effective_date,
unit_price,
prev_price,
next_price
FROM price_context
WHERE prev_price IS NOT NULL
AND next_price IS NOT NULL
AND ABS((unit_price - prev_price) / prev_price) > 0.30
AND ABS((unit_price - next_price) / next_price) > 0.30;
3. Google (Search, YouTube, Cloud, Ads)
Google SQL problems emphasize time-series sessionization, multi-attribution marketing models, search query transition n-grams, and percentile distribution over petabyte-scale event tables.
Question 13: 30-Minute Search Sessionization
- Company: Google
- Difficulty: Hard
- Core Concepts: Sessionization, Gaps-and-Islands, Cumulative Sum over Boolean Flags
Scenario & Schema
A search session is defined as a sequence of queries from the same user where no two consecutive searches are separated by more than 30 minutes. Assign a unique session_id to each query.
search_logs(search_id BIGINT, user_id BIGINT, query_text TEXT, searched_at TIMESTAMP)
Solution
WITH flagged_events AS (
SELECT
search_id,
user_id,
query_text,
searched_at,
CASE
WHEN searched_at - LAG(searched_at) OVER (PARTITION BY user_id ORDER BY searched_at ASC) > INTERVAL '30 minutes'
OR LAG(searched_at) OVER (PARTITION BY user_id ORDER BY searched_at ASC) IS NULL
THEN 1
ELSE 0
END AS is_new_session
FROM search_logs
),
sessionized AS (
SELECT
search_id,
user_id,
query_text,
searched_at,
SUM(is_new_session) OVER (PARTITION BY user_id ORDER BY searched_at ASC) AS user_session_seq
FROM flagged_events
)
SELECT
search_id,
user_id,
CONCAT(user_id, '_', user_session_seq) AS global_session_id,
searched_at,
query_text
FROM sessionized
ORDER BY user_id, searched_at ASC;
Why It Works & Architectural Mechanics
- Step 1: Compare each event’s timestamp to the previous timestamp using
LAG(). If the delta exceeds 30 minutes (or is NULL), mark it as the start of an island (1), otherwise0. - Step 2: Compute a running cumulative sum of these markers (
SUM(is_new_session) OVER (...)). Because the flag is0within an ongoing session, the sum stays constant, stamping the same session number onto all events within that cluster.
Question 14: Top 5th Percentile Click-Through-Rate (CTR) Queries
- Company: Google
- Difficulty: Medium
- Core Concepts:
PERCENT_RANK(),NTILE(), Ad-Tech Analytics
Scenario & Schema
Identify top-performing search queries whose Click-Through Rate ($CTR = \frac{\text{clicks}}{\text{impressions}}$) places them in the top 5% of their language market. Exclude queries with fewer than 1,000 impressions.
query_metrics(query_id BIGINT, market VARCHAR(8), impressions INT, clicks INT)
Solution
WITH calculated_ctr AS (
SELECT
query_id,
market,
impressions,
clicks,
(clicks::NUMERIC / impressions) AS ctr,
PERCENT_RANK() OVER (
PARTITION BY market
ORDER BY (clicks::NUMERIC / impressions) ASC
) AS rank_pct
FROM query_metrics
WHERE impressions >= 1000
)
SELECT
query_id,
market,
impressions,
clicks,
ROUND(ctr * 100, 3) AS ctr_pct
FROM calculated_ctr
WHERE rank_pct >= 0.95
ORDER BY market, ctr_pct DESC;
Why It Works & Architectural Mechanics
PERCENT_RANK()calculates relative rank as $\frac{\text{rank} - 1}{\text{total rows} - 1}$, producing values strictly between $0.0$ and $1.0$.- Ranking only queries with $\ge 1000$ impressions prevents skew from low-sample anomalies (e.g., 1 impression, 1 click = 100% CTR).
Question 15: First-Touch vs Last-Touch Ad Conversion Attribution
- Company: Google
- Difficulty: Hard
- Core Concepts: Multi-Touch Attribution,
FIRST_VALUE,LAST_VALUE, Window Framing
Scenario & Schema
An advertiser receives conversions from users who interacted with multiple ad campaigns over a 14-day window. Attribute 50% of the revenue to the First-Touch campaign and 50% to the Last-Touch campaign.
user_ad_clicks(click_id BIGINT, user_id BIGINT, campaign_id INT, clicked_at TIMESTAMP)conversions(conversion_id BIGINT, user_id BIGINT, conversion_value NUMERIC(10,2), converted_at TIMESTAMP)
Solution
WITH attributed_clicks AS (
SELECT
c.conversion_id,
c.user_id,
c.conversion_value,
FIRST_VALUE(a.campaign_id) OVER (
PARTITION BY c.conversion_id
ORDER BY a.clicked_at ASC
ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
) AS first_touch_campaign,
LAST_VALUE(a.campaign_id) OVER (
PARTITION BY c.conversion_id
ORDER BY a.clicked_at ASC
ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
) AS last_touch_campaign
FROM conversions c
JOIN user_ad_clicks a
ON c.user_id = a.user_id
AND a.clicked_at BETWEEN c.converted_at - INTERVAL '14 days' AND c.converted_at
),
deduped_conversions AS (
SELECT DISTINCT
conversion_id,
conversion_value,
first_touch_campaign,
last_touch_campaign
FROM attributed_clicks
)
SELECT
campaign_id,
ROUND(SUM(allocated_revenue), 2) AS total_attributed_revenue
FROM (
SELECT first_touch_campaign AS campaign_id, conversion_value * 0.5 AS allocated_revenue FROM deduped_conversions
UNION ALL
SELECT last_touch_campaign AS campaign_id, conversion_value * 0.5 AS allocated_revenue FROM deduped_conversions
) split_attributions
GROUP BY campaign_id
ORDER BY total_attributed_revenue DESC;
Common Traps
- Omitting
ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWINGwhen callingLAST_VALUE(): by default, window frames terminate atCURRENT ROW, which causesLAST_VALUE()to return the current row instead of the final row!
Question 16: YouTube Video Audience Retention (Seconds Drop-off Curve)
- Company: Google
- Difficulty: Medium
- Core Concepts: Video Telemetry, Aggregating Playback Checkpoints
Scenario & Schema
For a specific video (video_id = 101), determine the percentage of viewers retained at each 10-second playback bucket relative to total viewers who started the video.
video_watch_logs(session_id BIGINT, video_id BIGINT, watch_seconds INT)
Solution
WITH total_starts AS (
SELECT COUNT(DISTINCT session_id) AS initial_viewers
FROM video_watch_logs
WHERE video_id = 101 AND watch_seconds >= 0
),
playback_buckets AS (
SELECT generate_series(0, 180, 10) AS milestone_seconds
),
viewers_per_milestone AS (
SELECT
b.milestone_seconds,
COUNT(DISTINCT l.session_id) AS remaining_viewers
FROM playback_buckets b
LEFT JOIN video_watch_logs l
ON l.video_id = 101
AND l.watch_seconds >= b.milestone_seconds
GROUP BY b.milestone_seconds
)
SELECT
m.milestone_seconds,
m.remaining_viewers,
ROUND((m.remaining_viewers::NUMERIC / s.initial_viewers) * 100, 2) AS retention_rate_pct
FROM viewers_per_milestone m
CROSS JOIN total_starts s
ORDER BY m.milestone_seconds ASC;
Question 17: Advertiser Daily Spend Anomalies (Z-Score Deviation)
- Company: Google
- Difficulty: Hard
- Core Concepts: Standard Deviation (
STDDEV), Statistical Process Control, Outlier Detection
Scenario & Schema
Identify advertisers whose spend yesterday exceeded 3 standard deviations above their 30-day historical mean ($Z > 3$).
daily_ad_spend(advertiser_id INT, spend_date DATE, spend_amount NUMERIC(12,2))
Solution
WITH stats AS (
SELECT
advertiser_id,
spend_date,
spend_amount,
AVG(spend_amount) OVER (
PARTITION BY advertiser_id
ORDER BY spend_date ASC
ROWS BETWEEN 30 PRECEDING AND 1 PRECEDING
) AS avg_spend_30d,
STDDEV(spend_amount) OVER (
PARTITION BY advertiser_id
ORDER BY spend_date ASC
ROWS BETWEEN 30 PRECEDING AND 1 PRECEDING
) AS stddev_spend_30d
FROM daily_ad_spend
)
SELECT
advertiser_id,
spend_date,
spend_amount,
ROUND(avg_spend_30d, 2) AS historical_mean,
ROUND(stddev_spend_30d, 2) AS historical_stddev,
ROUND(((spend_amount - avg_spend_30d) / NULLIF(stddev_spend_30d, 0)), 2) AS z_score
FROM stats
WHERE spend_date = CURRENT_DATE - INTERVAL '1 day'
AND stddev_spend_30d > 0
AND (spend_amount - avg_spend_30d) / stddev_spend_30d > 3.0;
Question 18: Search Transition Bigrams (N-gram Sequences)
- Company: Google
- Difficulty: Hard
- Core Concepts: Natural Language Query Sequencing,
LEAD(), Transition Frequency
Scenario & Schema
Find the top 5 most common follow-up search queries for users whose initial search contained the keyword 'sql'.
searches(user_id BIGINT, query_clean VARCHAR(255), search_time TIMESTAMP)
Solution
WITH sequential_queries AS (
SELECT
user_id,
query_clean AS current_query,
LEAD(query_clean, 1) OVER (PARTITION BY user_id ORDER BY search_time ASC) AS next_query,
LEAD(search_time, 1) OVER (PARTITION BY user_id ORDER BY search_time ASC) AS next_search_time,
search_time
FROM searches
)
SELECT
current_query,
next_query,
COUNT(*) AS transition_count
FROM sequential_queries
WHERE current_query LIKE '%sql%'
AND next_query IS NOT NULL
AND next_search_time <= search_time + INTERVAL '10 minutes'
GROUP BY current_query, next_query
ORDER BY transition_count DESC
LIMIT 5;
4. Microsoft (Azure, Teams, Office 365, LinkedIn)
Microsoft queries feature dense calendar dimension mapping, resource utilization billing, hierarchical self-joins, and subscription revenue waterfalls.
Question 19: Continuous Calendar Fill for Sparse Telemetry
- Company: Microsoft
- Difficulty: Hard
- Core Concepts:
generate_series, Date Dimension Scaffolding, Zero-Filling Sparse Data
Scenario & Schema
Telemetry log tables omit days where users performed no activity. Generate a complete daily count of active users per tenant for every calendar day in September 2026, reporting 0 for inactive days.
tenant_logins(tenant_id INT, login_date DATE, user_id INT)
Solution
WITH calendar AS (
SELECT generate_series('2026-09-01'::DATE, '2026-09-30'::DATE, INTERVAL '1 day')::DATE AS cal_date
),
tenants AS (
SELECT DISTINCT tenant_id FROM tenant_logins
),
tenant_scaffold AS (
SELECT t.tenant_id, c.cal_date
FROM tenants t
CROSS JOIN calendar c
),
daily_distinct_logins AS (
SELECT
tenant_id,
login_date,
COUNT(DISTINCT user_id) AS active_users
FROM tenant_logins
WHERE login_date BETWEEN '2026-09-01' AND '2026-09-30'
GROUP BY tenant_id, login_date
)
SELECT
s.tenant_id,
s.cal_date,
COALESCE(l.active_users, 0) AS active_users
FROM tenant_scaffold s
LEFT JOIN daily_distinct_logins l
ON s.tenant_id = l.tenant_id
AND s.cal_date = l.login_date
ORDER BY s.tenant_id, s.cal_date ASC;
Why It Works & Architectural Mechanics
- A
CROSS JOINbetween all tenants and the complete calendar series guarantees an anchor row exists for every single date. LEFT JOINpreserved byCOALESCE(..., 0)guarantees that inactive days are not swallowed by empty sets.
Question 20: Microsoft Teams Peak Concurrent Meeting Audio Streams
- Company: Microsoft
- Difficulty: Hard
- Core Concepts: Point-in-Time Concurrency, Double Event Decomposition (+1 / -1), Running Totals
Scenario & Schema
Given meeting start and end times, compute the maximum number of simultaneously active audio streams across an enterprise tenant.
meeting_audio(call_id BIGINT, tenant_id INT, start_time TIMESTAMP, end_time TIMESTAMP)
Solution
WITH endpoint_events AS (
SELECT tenant_id, start_time AS event_time, 1 AS stream_delta FROM meeting_audio
UNION ALL
SELECT tenant_id, end_time AS event_time, -1 AS stream_delta FROM meeting_audio
),
cumulative_concurrency AS (
SELECT
tenant_id,
event_time,
SUM(stream_delta) OVER (
PARTITION BY tenant_id
ORDER BY event_time ASC, stream_delta ASC
) AS current_active_streams
FROM endpoint_events
)
SELECT
tenant_id,
MAX(current_active_streams) AS peak_concurrent_streams
FROM cumulative_concurrency
GROUP BY tenant_id;
Why It Works & Architectural Mechanics
- Transforming intervals into discrete
+1(start) and-1(end) events reduces an $O(N^2)$ interval overlap query into an $O(N \log N)$ running total scan. - Ordering by
stream_delta ASCensures that call terminations (-1) are processed before call initiations (+1) at exact millisecond boundaries, preventing phantom concurrency spikes.
Question 21: Azure VM Resource Billing with Plan Transition Resets
- Company: Microsoft
- Difficulty: Hard
- Core Concepts: Running Accumulator, State Transition, Island Grouping
Scenario & Schema
Calculate the cumulative usage hours of an Azure VM instance, resetting the counter to 0 whenever the virtual machine tier changes.
vm_usage(vm_id INT, log_time TIMESTAMP, tier VARCHAR(16), hours_billed INT)
Solution
WITH tier_transitions AS (
SELECT
vm_id,
log_time,
tier,
hours_billed,
CASE
WHEN LAG(tier) OVER (PARTITION BY vm_id ORDER BY log_time ASC) = tier
THEN 0
ELSE 1
END AS is_plan_change
FROM vm_usage
),
grouped_tiers AS (
SELECT
vm_id,
log_time,
tier,
hours_billed,
SUM(is_plan_change) OVER (PARTITION BY vm_id ORDER BY log_time ASC) AS tier_group_id
FROM tier_transitions
)
SELECT
vm_id,
log_time,
tier,
hours_billed,
SUM(hours_billed) OVER (
PARTITION BY vm_id, tier_group_id
ORDER BY log_time ASC
) AS running_tier_hours
FROM grouped_tiers
ORDER BY vm_id, log_time ASC;
Question 22: Hierarchical Management Span (Recursive Organizational Chart)
- Company: Microsoft
- Difficulty: Hard
- Core Concepts: Recursive CTEs (
WITH RECURSIVE), Directed Acyclic Graphs (DAG), Hierarchy Traversal
Scenario & Schema
Given an employee directory, write a recursive query to find the total headcount (all direct and indirect reports) under VP employee_id = 10.
employees(employee_id INT, manager_id INT, name VARCHAR(64))
Solution
WITH RECURSIVE org_hierarchy AS (
-- Anchor member: Direct reports of employee 10
SELECT employee_id, manager_id, 1 AS depth
FROM employees
WHERE manager_id = 10
UNION ALL
-- Recursive member: Reports of reports
SELECT e.employee_id, e.manager_id, h.depth + 1
FROM employees e
JOIN org_hierarchy h ON e.manager_id = h.employee_id
)
SELECT
10 AS leader_id,
COUNT(employee_id) AS total_reporting_headcount,
MAX(depth) AS max_organization_depth
FROM org_hierarchy;
Question 23: SaaS License Underutilization Audit
- Company: Microsoft
- Difficulty: Medium
- Core Concepts: Joins, Proportional Aggregation, Cost Optimization
Scenario & Schema
Find Microsoft 365 enterprise customers who have utilized fewer than 60% of their purchased license seats over the past 30 days.
contracts(tenant_id INT, purchased_seats INT)seat_activity(tenant_id INT, user_id INT, last_active_date DATE)
Solution
WITH active_tenant_seats AS (
SELECT
tenant_id,
COUNT(DISTINCT user_id) AS active_seat_count
FROM seat_activity
WHERE last_active_date >= CURRENT_DATE - INTERVAL '30 days'
GROUP BY tenant_id
)
SELECT
c.tenant_id,
c.purchased_seats,
COALESCE(a.active_seat_count, 0) AS active_seats,
ROUND((COALESCE(a.active_seat_count, 0)::NUMERIC / c.purchased_seats) * 100, 2) AS utilization_pct
FROM contracts c
LEFT JOIN active_tenant_seats a ON c.tenant_id = a.tenant_id
WHERE (COALESCE(a.active_seat_count, 0)::NUMERIC / c.purchased_seats) < 0.60
ORDER BY utilization_pct ASC;
Question 24: Rolling 30-Day Customer Subscription Churn
- Company: Microsoft
- Difficulty: Hard
- Core Concepts: Rolling Aggregations, Churn Cohorts, Window Framing
Scenario & Schema
Compute the rolling 30-day subscription churn rate for each day in Q3 2026.
subscriptions(sub_id BIGINT, start_date DATE, churn_date DATE)
Solution
WITH calendar AS (
SELECT generate_series('2026-07-01'::DATE, '2026-09-30'::DATE, INTERVAL '1 day')::DATE AS report_date
)
SELECT
c.report_date,
COUNT(DISTINCT CASE
WHEN s.churn_date BETWEEN c.report_date - INTERVAL '29 days' AND c.report_date
THEN s.sub_id
END) AS churned_subs_30d,
COUNT(DISTINCT CASE
WHEN s.start_date <= c.report_date
AND (s.churn_date IS NULL OR s.churn_date >= c.report_date - INTERVAL '29 days')
THEN s.sub_id
END) AS active_subs_base,
ROUND(
COUNT(DISTINCT CASE WHEN s.churn_date BETWEEN c.report_date - INTERVAL '29 days' AND c.report_date THEN s.sub_id END)::NUMERIC
/ NULLIF(COUNT(DISTINCT CASE WHEN s.start_date <= c.report_date AND (s.churn_date IS NULL OR s.churn_date >= c.report_date - INTERVAL '29 days') THEN s.sub_id END), 0) * 100,
2
) AS rolling_30d_churn_pct
FROM calendar c
CROSS JOIN subscriptions s
GROUP BY c.report_date
ORDER BY c.report_date ASC;
5. Apple (App Store, Services, Hardware Ecosystem)
Apple technical screens evaluate device ecosystem cross-sell affinity, App Store rank preservation with ties, subscription renewals, and currency normalization.
Question 25: App Store Top 3 Apps Per Category (Preserving Ties)
- Company: Apple
- Difficulty: Medium
- Core Concepts: Window Functions,
DENSE_RANK(), Tie Preservation
Scenario & Schema
Find the top 3 highest grossing apps in each App Store category. If two apps have identical revenue, both must share the rank without skipping subsequent ranks.
app_sales(app_id INT, category_id INT, total_gross NUMERIC(12,2))
Solution
WITH ranked_apps AS (
SELECT
app_id,
category_id,
total_gross,
DENSE_RANK() OVER (
PARTITION BY category_id
ORDER BY total_gross DESC
) AS rank_tier
FROM app_sales
)
SELECT
category_id,
rank_tier,
app_id,
total_gross
FROM ranked_apps
WHERE rank_tier <= 3
ORDER BY category_id, rank_tier ASC, total_gross DESC;
Why It Works & Architectural Mechanics
DENSE_RANK()does not produce numerical gaps after ties (e.g.,1, 1, 2, 3), ensuring that exactly 3 distinct revenue tiers are returned per category.
Question 26: Hardware Ecosystem Cross-Selling Affinity
- Company: Apple
- Difficulty: Hard
- Core Concepts: Relational Pair Combinations, Self-Joins, Market Basket Analysis
Scenario & Schema
Find the product pair (Product A and Product B) most frequently purchased together across unique customer hardware registration profiles.
device_registrations(customer_id BIGINT, product_model VARCHAR(64), registered_at TIMESTAMP)
Solution
SELECT
r1.product_model AS product_a,
r2.product_model AS product_b,
COUNT(DISTINCT r1.customer_id) AS shared_customers_count
FROM device_registrations r1
JOIN device_registrations r2
ON r1.customer_id = r2.customer_id
AND r1.product_model < r2.product_model
GROUP BY r1.product_model, r2.product_model
ORDER BY shared_customers_count DESC
LIMIT 5;
Why It Works & Architectural Mechanics
r1.product_model < r2.product_modelprevents self-matches (iPhonewithiPhone) and eliminates mirrored duplicate pairs (iPhone + MacvsMac + iPhone).
Question 27: Free Trial to Paid Subscription Conversion by Device Family
- Company: Apple
- Difficulty: Medium
- Core Concepts: Conversion Ratios, Device Segmentation, Conditional Rates
Scenario & Schema
Calculate the conversion rate from Apple One Free Trial to a paid subscription, broken down by initial enrollment device family (iPhone, iPad, Mac).
subscriptions(sub_id BIGINT, user_id BIGINT, device_family VARCHAR(16), trial_start_date DATE, first_billing_date DATE)
Solution
SELECT
device_family,
COUNT(sub_id) AS total_trials_started,
COUNT(first_billing_date) AS converted_paid_subs,
ROUND(
(COUNT(first_billing_date)::NUMERIC / NULLIF(COUNT(sub_id), 0)) * 100,
2
) AS conversion_rate_pct
FROM subscriptions
WHERE trial_start_date BETWEEN '2026-01-01' AND '2026-06-30'
GROUP BY device_family
ORDER BY conversion_rate_pct DESC;
Question 28: App Store Rating Decay (Time-Weighted Moving Average)
- Company: Apple
- Difficulty: Hard
- Core Concepts: Exponential Decay, Mathematical Modeling in SQL
Scenario & Schema
Compute an exponential time-weighted average rating for app 404, discounting review weight by half for reviews older than 90 days.
app_reviews(review_id BIGINT, app_id INT, rating INT, review_date DATE)
Solution
WITH weighted_reviews AS (
SELECT
rating,
review_date,
POWER(0.5, (CURRENT_DATE - review_date)::NUMERIC / 90.0) AS review_weight
FROM app_reviews
WHERE app_id = 404
)
SELECT
ROUND(SUM(rating * review_weight) / NULLIF(SUM(review_weight), 0), 2) AS time_decayed_rating,
COUNT(*) AS total_reviews
FROM weighted_reviews;
Question 29: Customer Hardware Upgrade Cycle Duration
- Company: Apple
- Difficulty: Medium
- Core Concepts:
LEAD(), Day Interval Calculations, Median Lifecycle
Scenario & Schema
Calculate the average number of months elapsed between a user registering their first iPhone and their subsequent iPhone purchase.
device_purchases(customer_id BIGINT, device_type VARCHAR(32), purchase_date DATE)
Solution
WITH iphone_sequence AS (
SELECT
customer_id,
purchase_date,
LEAD(purchase_date) OVER (
PARTITION BY customer_id
ORDER BY purchase_date ASC
) AS next_iphone_purchase
FROM device_purchases
WHERE device_type = 'iPhone'
)
SELECT
ROUND(AVG(next_iphone_purchase - purchase_date) / 30.4375, 1) AS avg_upgrade_cycle_months
FROM iphone_sequence
WHERE next_iphone_purchase IS NOT NULL;
Question 30: Multi-Currency App Store Revenue Conversion
- Company: Apple
- Difficulty: Hard
- Core Concepts: Currency Conversion, Daily FX Rate Mapping, Correlated Lookups
Scenario & Schema
Convert global daily in-app purchase revenue into USD based on closing daily FX exchange rates.
transactions(txn_id BIGINT, txn_date DATE, currency VARCHAR(3), local_amount NUMERIC(10,2))fx_rates(rate_date DATE, currency VARCHAR(3), usd_conversion_factor NUMERIC(10,6))
Solution
SELECT
t.txn_date,
t.currency,
SUM(t.local_amount) AS total_local_revenue,
ROUND(SUM(t.local_amount * f.usd_conversion_factor), 2) AS total_usd_revenue
FROM transactions t
JOIN fx_rates f
ON t.txn_date = f.rate_date
AND t.currency = f.currency
GROUP BY t.txn_date, t.currency
ORDER BY t.txn_date ASC, total_usd_revenue DESC;
6. Netflix (Streaming, Content Analytics, Playback Telemetry)
Netflix interviews test interval stitching for binge-watching sessions, A/B testing variant significance, churn event attribution, and content overlap metrics.
Question 31: Binge-Watching Session Interval Stitching
- Company: Netflix
- Difficulty: Hard
- Core Concepts: Interval Consolidation, Gaps-and-Islands, Session Boundary Stitching
Scenario & Schema
A binge session is defined as continuous playback where the gap between the end of one video and the start of the next video is less than or equal to 15 minutes. Find the total duration of each stitched binge session.
playback_streams(stream_id BIGINT, user_id BIGINT, start_time TIMESTAMP, end_time TIMESTAMP)
Solution
WITH stream_gaps AS (
SELECT
stream_id,
user_id,
start_time,
end_time,
CASE
WHEN start_time - MAX(end_time) OVER (
PARTITION BY user_id
ORDER BY start_time ASC
ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING
) <= INTERVAL '15 minutes'
THEN 0
ELSE 1
END AS is_new_binge_session
FROM playback_streams
),
binge_clusters AS (
SELECT
user_id,
start_time,
end_time,
SUM(is_new_binge_session) OVER (
PARTITION BY user_id
ORDER BY start_time ASC
) AS binge_id
FROM stream_gaps
)
SELECT
user_id,
binge_id,
MIN(start_time) AS binge_start,
MAX(end_time) AS binge_end,
COUNT(*) AS episodes_watched,
EXTRACT(EPOCH FROM (MAX(end_time) - MIN(start_time))) / 3600.0 AS total_hours
FROM binge_clusters
GROUP BY user_id, binge_id
HAVING COUNT(*) >= 2
ORDER BY total_hours DESC;
Why It Works & Architectural Mechanics
- Tracks
MAX(end_time)of all preceding playback events to accommodate overlapping or out-of-order streams. - Aggregates by
binge_idto determine total continuous session duration.
Question 32: A/B Testing Variant Conversion Summary
- Company: Netflix
- Difficulty: Medium
- Core Concepts: A/B Test Aggregation, Conversion Rate, Pre-Experiment Normalization
Scenario & Schema
Compare streaming hours and 7-day retention across users randomly assigned to control and treatment UI test variants.
experiment_assignments(user_id BIGINT, variant VARCHAR(16), assigned_at TIMESTAMP)user_engagement(user_id BIGINT, stream_date DATE, watch_hours NUMERIC(6,2))
Solution
WITH variant_metrics AS (
SELECT
e.variant,
e.user_id,
COALESCE(SUM(u.watch_hours), 0) AS total_watch_hours,
CASE WHEN MAX(u.stream_date) >= e.assigned_at::DATE + INTERVAL '7 days' THEN 1 ELSE 0 END AS retained_7d
FROM experiment_assignments e
LEFT JOIN user_engagement u
ON e.user_id = u.user_id
AND u.stream_date BETWEEN e.assigned_at::DATE AND e.assigned_at::DATE + INTERVAL '14 days'
GROUP BY e.variant, e.user_id
)
SELECT
variant,
COUNT(user_id) AS sample_size,
ROUND(AVG(total_watch_hours), 2) AS mean_watch_hours,
ROUND(AVG(retained_7d) * 100, 2) AS retention_7d_pct
FROM variant_metrics
GROUP BY variant;
Question 33: Churn Driver: Last Watched Content Prior to Cancellation
- Company: Netflix
- Difficulty: Medium
- Core Concepts: Window Functions, Event Correlation, Churn Attribution
Scenario & Schema
Identify the specific title watched by a customer immediately prior to cancelling their subscription.
cancellations(user_id BIGINT, cancelled_at TIMESTAMP)viewing_history(user_id BIGINT, show_id INT, watched_at TIMESTAMP)shows(show_id INT, title VARCHAR(255))
Solution
WITH ranked_last_watch AS (
SELECT
c.user_id,
v.show_id,
v.watched_at,
ROW_NUMBER() OVER (
PARTITION BY c.user_id
ORDER BY v.watched_at DESC
) AS rank_order
FROM cancellations c
JOIN viewing_history v
ON c.user_id = v.user_id
AND v.watched_at <= c.cancelled_at
)
SELECT
s.title,
COUNT(r.user_id) AS churn_attribution_count
FROM ranked_last_watch r
JOIN shows s ON r.show_id = s.show_id
WHERE r.rank_order = 1
GROUP BY s.title
ORDER BY churn_attribution_count DESC
LIMIT 10;
Question 34: Content Recommendation Overlap (Jaccard Similarity)
- Company: Netflix
- Difficulty: Hard
- Core Concepts: Jaccard Metric, Set Overlap, Intersection over Union
Scenario & Schema
Calculate the Jaccard similarity coefficient between two TV shows based on viewer co-consumption: $$J(A, B) = \frac{|A \cap B|}{|A \cup B|} = \frac{|A \cap B|}{|A| + |B| - |A \cap B|}$$
viewers(user_id BIGINT, show_id INT)
Solution
WITH show_totals AS (
SELECT show_id, COUNT(DISTINCT user_id) AS total_viewers
FROM viewers
GROUP BY show_id
),
shared_viewers AS (
SELECT
v1.show_id AS show_a,
v2.show_id AS show_b,
COUNT(DISTINCT v1.user_id) AS common_viewers
FROM viewers v1
JOIN viewers v2
ON v1.user_id = v2.user_id
AND v1.show_id < v2.show_id
GROUP BY v1.show_id, v2.show_id
)
SELECT
s.show_a,
s.show_b,
s.common_viewers,
ROUND(
s.common_viewers::NUMERIC / (t1.total_viewers + t2.total_viewers - s.common_viewers),
4
) AS jaccard_similarity
FROM shared_viewers s
JOIN show_totals t1 ON s.show_a = t1.show_id
JOIN show_totals t2 ON s.show_b = t2.show_id
ORDER BY jaccard_similarity DESC
LIMIT 10;
Question 35: Rolling 7-Day Stream Hours: ROWS vs RANGE Semantics
- Company: Netflix
- Difficulty: Medium
- Core Concepts: Window Frame Semantics, Sparse Timeline Handling
Scenario & Schema
Calculate the rolling 7-day streaming duration per user. Demonstrate why RANGE over an interval must be used instead of ROWS when calendar days are sparse.
daily_viewing(user_id BIGINT, view_date DATE, hours NUMERIC(5,2))
Solution
SELECT
user_id,
view_date,
hours,
-- CORRECT: Aggregates across calendar interval regardless of missing days
SUM(hours) OVER (
PARTITION BY user_id
ORDER BY view_date ASC
RANGE BETWEEN INTERVAL '6 days' PRECEDING AND CURRENT ROW
) AS rolling_7d_hours_range,
-- INCORRECT FOR SPARSE DATA: Only looks back 6 available records
SUM(hours) OVER (
PARTITION BY user_id
ORDER BY view_date ASC
ROWS BETWEEN 6 PRECEDING AND CURRENT ROW
) AS rolling_6_records_hours_rows
FROM daily_viewing
ORDER BY user_id, view_date ASC;
Question 36: Resurrected / Reactivated User Detection
- Company: Netflix
- Difficulty: Hard
- Core Concepts: Customer Lifecycle, Dormancy Thresholds,
LAG()
Scenario & Schema
Identify “resurrected” subscribers: users who streamed content this month after having 0 streaming hours across the preceding 90 days.
streaming_events(user_id BIGINT, stream_time TIMESTAMP)
Solution
WITH user_monthly_streams AS (
SELECT
user_id,
DATE_TRUNC('month', stream_time)::DATE AS stream_month,
MIN(stream_time) AS first_stream_in_month
FROM streaming_events
GROUP BY user_id, DATE_TRUNC('month', stream_time)
),
dormancy_evaluated AS (
SELECT
user_id,
stream_month,
first_stream_in_month,
LAG(first_stream_in_month) OVER (
PARTITION BY user_id
ORDER BY stream_month ASC
) AS previous_stream_time
FROM user_monthly_streams
)
SELECT
user_id,
stream_month AS reactivation_month,
previous_stream_time,
first_stream_in_month,
EXTRACT(DAY FROM (first_stream_in_month - previous_stream_time)) AS dormant_days
FROM dormancy_evaluated
WHERE previous_stream_time IS NOT NULL
AND first_stream_in_month - previous_stream_time > INTERVAL '90 days'
ORDER BY reactivation_month DESC, user_id ASC;
Continue Your Preparation in Part 2 & Interactive Practice
You have mastered the foundational and distributed query patterns across Meta, Amazon, Google, Microsoft, Apple, and Netflix.
Now continue to Company-Wise SQL Interview Questions (Part 2: Marketplaces, Fintech & Unicorns), covering:
- Uber, DoorDash & Airbnb: Spatial logistics, trip interval collisions, and marketplace surge economics.
- Stripe, PayPal, PhonePe & Razorpay: Double-entry ledger balances, payment gateway failure streaks, and fraud velocity spikes.
- Spotify, LinkedIn & X (Twitter): Streaming longevity charts, recursive social graph traversal, and viral impression histograms.
- Walmart & Flipkart: Supply chain replenishment latencies and mega-sale concurrency bottlenecks.
Test Your Skills on Live Interview Challenges:
Ready to Level Up Your SQL?
Don't just read about databases. Write queries, build schemas, and practice real-world interview questions interactively.