← Back to SQL, page 4

sql-0077 · Easy fresher

Write a query for total revenue per month from the orders and order items tables.

Join orders to their items, compute qty * unit_price per line, and group by the month of the order date, such as strftime('%Y-%m', order_date) in SQLite or date_trunc('month', order_date) in PostgreSQL. Decide whether cancelled orders count and filter them in WHERE.

Full answer
sql
CREATE TABLE customers (
  id      INTEGER PRIMARY KEY,
  name    TEXT NOT NULL,
  country TEXT
);
CREATE TABLE orders (
  id          INTEGER PRIMARY KEY,
  customer_id INTEGER REFERENCES customers(id),
  order_date  TEXT NOT NULL,
  status      TEXT NOT NULL
);
CREATE TABLE order_items (
  order_id   INTEGER REFERENCES orders(id),
  product    TEXT NOT NULL,
  qty        INTEGER NOT NULL,
  unit_price INTEGER NOT NULL
);
INSERT INTO customers VALUES (1,'Ana','Spain'),(2,'Bilal','UAE'),(3,'Chloe','France'),(4,'Dev','India');
INSERT INTO orders VALUES
  (101,1,'2026-01-05','shipped'),(102,1,'2026-02-11','shipped'),
  (103,2,'2026-02-14','cancelled'),(104,3,'2026-03-01','shipped'),
  (105,2,'2026-03-09','pending'),(106,NULL,'2026-03-12','shipped');
INSERT INTO order_items VALUES
  (101,'Notebook',2,4),(101,'Pen',5,1),(102,'Bag',1,30),(103,'Pen',10,1),
  (104,'Notebook',3,4),(104,'Bag',1,30),(105,'Lamp',1,25),(106,'Pen',2,1);
sql
SELECT strftime('%Y-%m', o.order_date) AS month,
       SUM(i.qty * i.unit_price)        AS revenue
FROM orders o
JOIN order_items i ON i.order_id = o.id
WHERE o.status <> 'cancelled'
GROUP BY month
ORDER BY month;
monthrevenue
2026-0113
2026-0230
2026-0369

A few choices are built into this query.

The month is computed from the date. In SQLite, strftime('%Y-%m', ...) returns text like '2026-02', which sorts correctly. In PostgreSQL the usual form is date_trunc('month', order_date), which returns a timestamp at the start of the month:

sql
SELECT date_trunc('month', o.order_date)::date AS month,
       SUM(i.qty * i.unit_price)                AS revenue
FROM orders o
JOIN order_items i ON i.order_id = o.id
WHERE o.status <> 'cancelled'
GROUP BY 1
ORDER BY 1;
monthrevenue
2026-01-0113
2026-02-0130
2026-03-0169

Cancelled orders are excluded in WHERE. Whether that is right is a business rule, and it belongs in the query explicitly, not left to chance.

Revenue is computed per line, then summed. Summing qty and unit_price separately and multiplying the totals would be wrong whenever an order has lines with different prices.

Months with no orders do not appear. If the chart needs every month, generate a list of months (a calendar table or a recursive CTE) and LEFT JOIN the totals onto it.

sql
CREATE TABLE customers (
  id      INTEGER PRIMARY KEY,
  name    TEXT NOT NULL,
  country TEXT
);
CREATE TABLE orders (
  id          INTEGER PRIMARY KEY,
  customer_id INTEGER REFERENCES customers(id),
  order_date  TEXT NOT NULL,
  status      TEXT NOT NULL
);
CREATE TABLE order_items (
  order_id   INTEGER REFERENCES orders(id),
  product    TEXT NOT NULL,
  qty        INTEGER NOT NULL,
  unit_price INTEGER NOT NULL
);
INSERT INTO customers VALUES (1,'Ana','Spain'),(2,'Bilal','UAE'),(3,'Chloe','France'),(4,'Dev','India');
INSERT INTO orders VALUES
  (101,1,'2026-01-05','shipped'),(102,1,'2026-02-11','shipped'),
  (103,2,'2026-02-14','cancelled'),(104,3,'2026-03-01','shipped'),
  (105,2,'2026-03-09','pending'),(106,NULL,'2026-03-12','shipped');
INSERT INTO order_items VALUES
  (101,'Notebook',2,4),(101,'Pen',5,1),(102,'Bag',1,30),(103,'Pen',10,1),
  (104,'Notebook',3,4),(104,'Bag',1,30),(105,'Lamp',1,25),(106,'Pen',2,1);

SELECT strftime('%Y-%m', o.order_date) AS month,
       SUM(i.qty * i.unit_price)        AS revenue
FROM orders o
JOIN order_items i ON i.order_id = o.id
WHERE o.status <> 'cancelled'
GROUP BY month
ORDER BY month;

Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.

Key points

  • Group by a month expression of the order date
  • Compute line revenue before summing
  • Filter business exclusions such as cancelled orders in WHERE
  • Empty months need a generated month list and a LEFT JOIN

Common mistakes

  • Multiplying SUM(qty) by SUM(price)
  • Forgetting that months without orders vanish from the result

Follow-ups

  • How would you show months with zero revenue?
  • How would you compare each month with the previous one?

Tips

  • Say out loud which orders you excluded and why