Customer ID 1 meets the criteria because they made purchases on 25th Jan, 26th Jan, and 27th Jan – three consecutive days. Customer ID 2 does not meet the criteria because, although they made more than three purchases, the dates are not consecutive. Write an SQL query to find customer IDs of customers who have made purchases on at least three consecutive days.
1Times asked
Jul 2026Last seen
Jul 2026First seen
💡 Model Answer
The goal is to identify customers with a streak of at least three consecutive purchase dates. The solution uses window functions to detect gaps and then counts streak lengths.
sql
WITH ranked AS (
SELECT
customer_id,
purchase_date,
LAG(purchase_date) OVER (PARTITION BY customer_id ORDER BY purchase_date) AS prev_date
FROM purchases
),
streaks AS (
SELECT
customer_id,
purchase_date,
CASE
WHEN prev_date IS NULL OR purchase_date - prev_date > 1 THEN 1
ELSE 0
END AS new_streak
FROM ranked
),
grouped AS (
SELECT
customer_id,
SUM(new_streak) OVER (PARTITION BY customer_id ORDER BY purchase_date ROWS UNBOUNDED PRECEDING) AS grp,
COUNT(*) OVER (PARTITION BY customer_id, SUM(new_streak) OVER (PARTITION BY customer_id ORDER BY purchase_date ROWS UNBOUNDED PRECEDING)) AS streak_len
FROM streaks
)
SELECT DISTINCT customer_id
FROM grouped
WHERE streak_len >= 3;Explanation:
rankedgets the previous purchase date for each customer.streaksflags the start of a new streak when the gap is >1 day.groupedassigns a group id to each streak and counts its length.- Finally, we filter groups with length ≥ 3.
Time complexity is O(n) with a few window scans, and it scales to millions of rows. The query works on most SQL engines that support window functions (PostgreSQL, SQL Server, Oracle, MySQL 8+).
This answer was generated by AI for study purposes. Use it as a starting point — personalize it with your own experience.
🎤 Get questions like this answered in real-time
Assisting AI listens to your interview, captures questions live, and gives you instant AI-powered answers on a discreet on-screen overlay.
Get Assisting AI — Starts at ₹500