Find the Longest Run of Consecutive Order Days per Customer
Return the customer or customers with the longest run of back-to-back order days, with the first and last day of the run.
The challenge runs on the SQLabHub practice database (SQLite) and uses the orders table. You can solve it in the browser, with nothing to install.
Why this question comes up
The engagement team wants to know the longest run of consecutive days on which a customer ordered something, a standard "streak" metric. It is a classic gaps-and-islands problem: find the unbroken runs of dates, then measure them. On this data, repeat orders on back-to-back days are rare, so the answer is short; the technique is what carries over.
The task
Find the longest run of consecutive calendar days on which the same customer placed an order. Show the customer, the first and last day of the run and its length. If several customers share the longest run, show them all.
A correct answer returns 1 row with 4 columns: user_id, streak_start, streak_end, streak_days.
Tables used in this challenge
orders 200 rows
id INTEGER (PK) · user_id INTEGER · total REAL · discount REAL · item_count INTEGER · status TEXT · order_date TEXT · shipped_date TEXT · shipping_city TEXT · shipping_country TEXT
| id | user_id | total | discount | item_count | status | order_date | shipped_date | shipping_city | shipping_country |
|---|---|---|---|---|---|---|---|---|---|
The first rows of each table are shown. See how all the tables relate on the database schema page.
Expected output
| user_id | streak_start | streak_end | streak_days |
|---|---|---|---|
The complete result: 1 row. This is the output of the model solution on the practice database.
What you practise
- Choosing exactly which columns a query returns
- Filtering rows with a WHERE condition
- Removing duplicate rows with DISTINCT
- Summarising many rows into one value with COUNT, SUM, AVG, MIN or MAX
- Grouping by more than one column to get a row per combination
- Using the result of one query inside another
- Naming an intermediate result with a WITH clause and reading from it
- Working with dates in SQLite: strftime, julianday and DATE
- Numbering rows with ROW_NUMBER() to pick one or a few per group
- Restarting a window calculation for each group with PARTITION BY
- Sorting the result with ORDER BY
- Deriving a new column from an expression and naming it with an alias
Hint and approach
Try the challenge first. Open these only when you need them.
Show the hint
Within a run of consecutive days, the date minus ROW_NUMBER() is constant. Group by user and that value, then keep the runs as long as the longest.
Show the step-by-step approach
How the model solution is built, in the order the database evaluates it:
- Define a common table expression named
days:- Read from the
orderstable. - Return only the columns
user_idandorder_date. DISTINCTremoves duplicate rows, so each value appears once.
- Read from the
- Define a common table expression named
runs:- Read from the
daysCTE. - Number the rows with
ROW_NUMBER(), ordered byorder_date, restarting for eachuser_id. - Combine those values into
grp:julianday(order_date) - ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY order_date).
- Read from the
- Define a common table expression named
streaks:- Read from the
runsCTE. - Group the rows by
user_idandgrp, so the result has one row for each combination. - For each group, compute
MIN(order_date),MAX(order_date)andCOUNT(*).
- Read from the
- Read from the
streaksCTE. - Filter in
WHERE: keep the rows wherestreak_daysequals the value returned by a subquery. - The subquery runs once and returns a single value. It works like this:
- Read from the
streaksCTE. - Aggregate over all the rows that are left: compute
MAX(streak_days). With no GROUP BY, the result is a single row.
- Read from the
- Return only the columns
user_id,streak_start,streak_endandstreak_days. - Sort the result by
user_id.
Show the model solution
WITH days AS (
SELECT DISTINCT user_id, order_date FROM orders
),
runs AS (
SELECT user_id, order_date,
julianday(order_date) - ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY order_date) AS grp
FROM days
),
streaks AS (
SELECT user_id, MIN(order_date) AS streak_start, MAX(order_date) AS streak_end, COUNT(*) AS streak_days
FROM runs
GROUP BY user_id, grp
)
SELECT user_id, streak_start, streak_end, streak_days
FROM streaks
WHERE streak_days = (SELECT MAX(streak_days) FROM streaks)
ORDER BY user_id;This query produced the expected output above. Yours does not have to match it word for word: any query that returns the same rows is correct.
What to watch for
Within a run of consecutive days, the day number minus the row number is constant, so that difference identifies the run. Grouping by it and counting gives the run length. The dates are made distinct first: two orders on the same day would otherwise give that day two row numbers and break the run.
- ROW_NUMBER(). ROW_NUMBER() breaks ties arbitrarily. When the ORDER BY inside OVER does not identify one row, the row that gets number 1 can change between runs.
- PARTITION BY. PARTITION BY is not GROUP BY: it keeps every row and only decides which rows a window function looks at.
- CTE (WITH). A CTE exists only for the single statement it is attached to. It is not a temporary table and cannot be reused by the next query.
Related SQL challenges
- Calculate Month-over-Month Revenue Change per ProductSimilar levelHard
- Find the Top-Spending Customer in Each CountrySimilar levelHard
- Find the Amount of Each Customer's Most Recent OrderEasierMedium
- Find Each Customer's Largest Order in Every MonthSimilar levelHard
- Calculate Days Between Consecutive Orders per Customer with LAG()Similar levelHard
Same technique, other tables
More practice on this pattern with different columns:
Keep learning
- Lesson: ROW_NUMBER()
- Lesson: Window Functions
- Lesson: CTEs (WITH Clause)
- Lesson: GROUP BY Multiple Columns
- All SQL practice challenges, by difficulty and topic
- SQL interview questions with answers
- SQL Playground: run any query on the same database