HardSQL challenge #291WINDOW FUNCTIONPATTERNGROUP BY

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.

Solve This SQL Challenge

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

First 3 rows of the orders table
iduser_idtotaldiscountitem_countstatusorder_dateshipped_dateshipping_cityshipping_country
143321.680.259cancelled2024-04-24NULLDelhiIndia
2810.520.191delivered2024-03-152024-03-20ColumbusUSA
3136181.190.085delivered2023-02-152023-02-18ChicagoUSA

The first rows of each table are shown. See how all the tables relate on the database schema page.

Expected output

Expected output of the challenge
user_idstreak_startstreak_endstreak_days
472022-10-152022-10-162

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:

  1. Define a common table expression named days:
    1. Read from the orders table.
    2. Return only the columns user_id and order_date.
    3. DISTINCT removes duplicate rows, so each value appears once.
  2. Define a common table expression named runs:
    1. Read from the days CTE.
    2. Number the rows with ROW_NUMBER(), ordered by order_date, restarting for each user_id.
    3. Combine those values into grp: julianday(order_date) - ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY order_date).
  3. Define a common table expression named streaks:
    1. Read from the runs CTE.
    2. Group the rows by user_id and grp, so the result has one row for each combination.
    3. For each group, compute MIN(order_date), MAX(order_date) and COUNT(*).
  4. Read from the streaks CTE.
  5. Filter in WHERE: keep the rows where streak_days equals the value returned by a subquery.
  6. The subquery runs once and returns a single value. It works like this:
    1. Read from the streaks CTE.
    2. Aggregate over all the rows that are left: compute MAX(streak_days). With no GROUP BY, the result is a single row.
  7. Return only the columns user_id, streak_start, streak_end and streak_days.
  8. 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.
Solve This SQL Challenge

Same technique, other tables

More practice on this pattern with different columns:

Keep learning