SQL interview question: find the bugs in a churn query
Problem
Shared data rulesThe colleague’s query returns an empty table. For each acquisition channel, find August 2026 buyers who bought nothing in September: their number, August orders and August revenue.
Query to fix
Fix it freeWITH august_orders AS (
SELECT o.user_id,
u.acq_channel,
o.order_id,
o.amount_usd
FROM orders AS o
JOIN users AS u
ON u.user_id = o.user_id
WHERE o.status = 'delivered'
AND o.created_at >= '2026-08-01'
AND o.created_at < '2026-08-31'
),
september_buyers AS (
SELECT user_id
FROM orders
WHERE status = 'delivered'
AND created_at >= '2026-09-01'
)
SELECT acq_channel,
COUNT(DISTINCT user_id) AS churned_buyers,
COUNT(*) AS august_orders,
SUM(amount_usd) AS august_revenue_usd
FROM august_orders
WHERE user_id NOT IN (SELECT user_id FROM september_buyers)
GROUP BY acq_channel
Example
users| user_id | acq_channel |
|---|---|
| 1 | ads |
| 2 | organic |
| 3 | organic |
orders| order_id | user_id | created_at | status | amount_usd | Row note |
|---|---|---|---|---|---|
| 201 | 1 | 2026-08-10 12:00 | delivered | 30 | |
| 202 | 2 | 2026-08-31 18:00 | delivered | 36 | |
| 203 | 3 | 2026-08-20 14:00 | delivered | 22 | |
| 204 | 3 | 2026-09-05 10:00 | delivered | 25 | ← buyer 3 came back in September |
| 205 | NULL | 2026-09-10 15:00 | delivered | 14 | ← guest order |
- Order 204: buyer 3 came back in September
- Order 205: guest order
| acq_channel | churned_buyers | august_orders | august_revenue_usd |
|---|---|---|---|
| ads | 1 | 1 | 30 |
| organic | 1 | 1 | 36 |
Buyers 1 and 2 churned: they bought only in August. Buyer 3 bought in September too.
Fix it free
Fix the query — code checks it on PostgreSQL in your browser. No sign-up needed.