Home / SQL / Practice problems / Hard

Every month, even empty ones

Hardrow order matters

Show every month of 2025 (2025-01 to 2025-12) with its number of orders, including months with 0, in order.

Tables: customers(customer_id, name, city, country, joined) · products(product_id, name, category, price) · orders(order_id, customer_id, order_date, status) · order_items(order_id, product_id, quantity, unit_price)

Your query
Show the expected result
monthorders
2025-012
2025-023
2025-038
2025-045
2025-055
2025-062
2025-075
2025-086
2025-092
2025-106
2025-113
2025-124

12 rows

Show a solution
WITH RECURSIVE m(d) AS (SELECT '2025-01-01' UNION ALL SELECT date(d, '+1 month') FROM m WHERE d < '2025-12-01') SELECT strftime('%Y-%m', m.d) AS month, COUNT(o.order_id) AS orders FROM m LEFT JOIN orders o ON strftime('%Y-%m', o.order_date) = strftime('%Y-%m', m.d) GROUP BY month ORDER BY month;

SQL used

New to SQL? The free SQL course teaches everything these problems use, with a self-checking exercise in every lesson.