r/SolveSQL • u/Tiny_Neighborhood536 • Aug 17 '26
SQL Challenge #1 — Find the Customers Who Came Back 🧩
Let’s start with an interesting one!
You have an orders table:
order_id | customer_id | order_date | amount
---------|-------------|------------|-------
1 | 101 | 2026-01-05 | 500
2 | 102 | 2026-01-07 | 300
3 | 101 | 2026-01-20 | 700
4 | 103 | 2026-02-02 | 400
5 | 102 | 2026-02-10 | 600
6 | 101 | 2026-03-15 | 200
7 | 102 | 2026-03-18 | 800
8 | 103 | 2026-03-25 | 500
9 | 101 | 2026-04-01 | 900
Challenge 🎯
For each customer, find their longest gap in days between two consecutive orders.
Your output should contain:
customer_id
previous_order_date
next_order_date
gap_days
There’s a catch: If a customer has multiple gaps tied for their longest gap, return all of them.
For example, if a customer’s orders were:
Jan 1 → Jan 10 → Jan 19
Both gaps are 9 days, so both should be returned.
Rules
Don’t hardcode customer IDs.
Only compare consecutive orders.
Return all ties.
Try solving it without a self-join. 👀
Bonus: Can you solve it without using a CTE?
Drop your SQL approach below! If someone has already solved it, try finding a different approach. 👇
3
u/Tiny_Neighborhood536 Aug 17 '26
I approached it using window functions.
First used LAG() partitioned by customer and ordered by order date to get the previous order for each row.
Once I had the current and previous order dates,
-> I calculated the difference between them to get the gap in days.
Then for each customer, I ranked those gaps from largest to smallest using DENSE_RANK() instead of ROW_NUMBER().
Finally, just filter for rank = 1.
So basically:
LAG() → calculate gap → rank gaps per customer → keep rank 1
There might be a cleaner way to do this though. Curious to see other approaches 👀
1
u/Brilliant-Parsley69 Aug 18 '26 edited Aug 18 '26
You almost got me with the no CTE bonus requirement, because normally you wouldn't nest this kind query three times. Especially if you expect a bigger dataset. You also could use a tmp table, to avoid multiple queries on the origin, but I wasn't sure if this would be an allowed solution.
SQL-Server:
1
u/franksta Aug 19 '26
My solution is basically the same as everyone else here.