TGViewer
Data Analytics Data Analytics @sqlspecialist ยท 111K subscribers
Post #2925 4.39K
๐—œ๐—ป๐˜๐—ฒ๐—ฟ๐˜ƒ๐—ถ๐—ฒ๐˜„๐—ฒ๐—ฟ:
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!
  • โค 8
More from @sqlspecialist
  1. Oct 8, 2026๐ŸŽ“ ๐— ๐—ถ๐—ฐ๐—ฟ๐—ผ๐˜€๐—ผ๐—ณ๐˜ ๐—™๐—ฅ๐—˜๐—˜ ๐—–๐—ผ๐˜‚๐—ฟ๐˜€๐—ฒ๐˜€ ๐˜„๐—ถ๐˜๐—ต ๐—–๐—ฒ๐—ฟ๐˜๐—ถ๐—ณ๐—ถ๐—ฐ๐—ฎ๐˜๐—ฒ๐˜€! ๐Ÿš€๐Ÿ”ฅ Upgrโ€ฆ
  2. Oct 7, 2026๐Ÿ“Š Kandinsky 6.0 Video: AI-Powered Content Creation for Analysts The new Kandinsky 6.0 Vidโ€ฆ
  3. Oct 7, 2026Alternatively, depending on the Excel version and requirement, I could use functions suchโ€ฆ
  4. Oct 7, 2026๐Ÿ“Š Data Analyst Interview Series โ€” Part 5 Guys, let's continue our Data Analyst Interviewโ€ฆ
  5. Oct 7, 2026๐Ÿš€๐—ฃ๐—ฎ๐˜† ๐—”๐—ณ๐˜๐—ฒ๐—ฟ ๐—ฃ๐—น๐—ฎ๐—ฐ๐—ฒ๐—บ๐—ฒ๐—ป๐˜ ๐—ง๐—ฟ๐—ฎ๐—ถ๐—ป๐—ถ๐—ป๐—ด | ๐—•๐—ฒ๐—ฐ๐—ผ๐—บ๐—ฒ ๐—ฎ ๐—™๐˜‚๐—น๐—น๐˜€๐˜๐—ฎ๐—ฐโ€ฆ
  6. Oct 7, 2026๐Ÿ”Ÿ What is the difference between UNION and JOIN? Sample Answer: "JOIN combines columns frโ€ฆ
Threads Profile ViewerView any public Threads profile without an account.Open ThreadLook โ†’Writing with AI? Make it sound human.Metric37 rewrites AI drafts so they read naturally. Free AI detector, 1,500 words free.Try Metric37 โ†’