๐—œ๐—ป๐˜๐—ฒ๐—ฟ๐˜ƒ๐—ถ๐—ฒ๐˜„๐—ฒ๐—ฟ: You have 2 minutes to solve this SQL queryโ€ฆ

๐—œ๐—ป๐˜๐—ฒ๐—ฟ๐˜ƒ๐—ถ๐—ฒ๐˜„๐—ฒ๐—ฟ:
You have 2 minutes to solve this SQL query.

Find the customers who placed orders on three or more consecutive days.

Assume the table structure:
orders(order_id, customer_id, order_date)

๐— ๐—ฒ: Challenge accepted! ๐Ÿ’ช

WITH consecutive_orders AS (
SELECT
customer_id,
order_date,
DATE_SUB(
order_date,
INTERVAL ROW_NUMBER() OVER (
PARTITION BY customer_id
ORDER BY order_date
) DAY
) AS grp
FROM (
SELECT DISTINCT
customer_id,
order_date
FROM orders
) t
)
SELECT
customer_id
FROM consecutive_orders
GROUP BY
customer_id,
grp
HAVING COUNT(*) >= 3;

๐Ÿ’ก Explanation:
This query identifies sequences of consecutive order dates for each customer.

โ€ข ROW_NUMBER() assigns a sequence number to each order date per customer.
โ€ข Subtracting the row number from the order date creates the same grp value for consecutive dates.
โ€ข GROUP BY customer_id, grp groups each consecutive streak.
โ€ข **HAVING COUNT(*) >= 3** returns customers with a streak of at least three consecutive days.

This question tests your understanding of: Common Table Expressions (CTEs), Window Functions (ROW_NUMBER()), Gaps and Islands Problem, Date Arithmetic.

๐ŸŽฏ Expected Output Example
Customer ID
101
205

(Customer 101 ordered on June 1, 2, and 3. Customer 205 ordered on July 10, 11, and 12.)

๐Ÿš€ Tip for SQL Job Seekers:
The Gaps and Islands pattern is one of the most advanced and frequently discussed SQL interview topics.

Master it for solving:
โ€ข Consecutive login days
โ€ข Consecutive purchases
โ€ข Attendance streaks
โ€ข Consecutive transactions
โ€ข User activity analysis

Being comfortable with this pattern can set you apart in technical interviews.

โค๏ธ React with โค๏ธ for more SQL interview challenges!
โค4
November 23, 2026 755 1