Subqueries and CTEs · Problem 68 of 118

Days Without Orders

HardSubqueries and CTEsShop data

Return every date from '2024-01-01' to '2024-01-31' on which no order was placed, as day, sorted by day.

Hint 1

GROUP BY can only show days that exist in the data. Generate the 31 dates yourself, then look for the ones with no matching order.

Hint 2

DATE(d, '+1 day') adds one day to a date.

Reference solution

WITH RECURSIVE days(day) AS (
  SELECT '2024-01-01'
  UNION ALL
  SELECT DATE(day, '+1 day') FROM days WHERE day < '2024-01-31'
)
SELECT d.day
FROM days AS d
LEFT JOIN orders AS o ON o.order_date = d.day
WHERE o.order_id IS NULL
ORDER BY d.day;

A report built from the data can only show what is in the data: a day with no orders has no row to group. To report on absences, generate the complete list of expected values (a calendar) and LEFT JOIN the data onto it; unmatched rows are your answer. The same trick fills the gaps in time-series charts with zeros.

Another way. A NOT IN version. It is safe here because order_date is never NULL, but NOT EXISTS would be the safer habit.

WITH RECURSIVE days(day) AS (
  SELECT '2024-01-01'
  UNION ALL
  SELECT DATE(day, '+1 day') FROM days WHERE day < '2024-01-31'
)
SELECT day
FROM days
WHERE day NOT IN (SELECT order_date FROM orders)
ORDER BY day;