Home / SQL / Practice problems / Hard

Change from the previous month

Hardrow order matters

For each month, show orders and change: orders minus the previous month's orders (NULL for the first month), in month 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
monthorderschange
2025-012NULL
2025-0231
2025-0385
2025-045-3
2025-0550
2025-062-3
2025-0753
2025-0861
2025-092-4
2025-1064
2025-113-3
2025-1241

12 rows

Show a solution
WITH m AS (SELECT strftime('%Y-%m', order_date) AS month, COUNT(*) AS orders FROM orders GROUP BY month) SELECT month, orders, orders - LAG(orders) OVER (ORDER BY month) AS change FROM m 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.