SQL Interview Trap ๐จ Consecutive Orders Logic
You have a table:
orders
order_id | customer_id | order_date | amount
๐ Question:
Find customers who placed orders on 3 or more consecutive days,
but return only the first date of each such streak per customer.
โ ๏ธ No temp tables.
โ ๏ธ Assume multiple orders per day are possible.
๐ง Most candidates fail because they:
- Forget to handle multiple orders on the same day
- Misuse ROW_NUMBER()
- Miss the date gap logic
โ
Correct SQL Solution:
WITH distinct_orders AS (
SELECT DISTINCT customer_id, order_date
FROM orders
),
grp AS (
SELECT
customer_id,
order_date,
order_date - INTERVAL '1 day' *
ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY order_date) AS grp_id
FROM distinct_orders
)
SELECT
customer_id,
MIN(order_date) AS streak_start_date
FROM grp
GROUP BY customer_id, grp_id
HAVING COUNT(*) >= 3;
๐ก Why this works (Interview Gold):
- DISTINCT removes same-day duplicates
- ROW_NUMBER() creates a sequence
- Date minus row number groups consecutive dates
- HAVING COUNT(*) >= 3 filters valid streaks
๐ฅ React with ๐ฅ if this bent your brain
๐ Follow the channel for REAL interview-level SQL Content
Post #2294
3.58K
- โค 7