r/learnSQL • u/shah-26 • Oct 29 '26
SQL puzzle: what's total March revenue from these two tables?
I'm practising SQL and came across this question. Curious how others would solve it.
Question: What was our total revenue for March 2026?
orders has one row per order. order_total is the full order amount.
order_items has one row per item in an order, linked by order_id.
orders:
order_id customer_id order_date order_total
1 101 2026-03-02 50
2 102 2026-03-05 120
3 103 2026-03-09 25
4 101 2026-03-12 90
5 104 2026-03-18 200
6 105 2026-03-21 35
7 102 2026-03-27 60
8 106 2026-02-26 80
order_items:
item_id order_id product item_price
1 1 Notebook 30
2 1 Pen set 20
3 2 Backpack 60
4 2 Lamp 40
5 2 Mug 20
6 3 Poster 25
7 4 Headphones. 70
8 4 Cable 20
9 5 Desk mat 80
10 5 Keyboard 50
11 5 Mouse 40
12 5 Stand 30
13 6 Cap 35
14 7 Bottle 35
15 7 Towel 25
16 8 Socks 50
17 8 Scarf 30
What's your query, and what number do you get? I'll post the answer in a few days.
Also curious: have you made a mistake like this at work or in an interview?
2
u/jayjetley Oct 29 '26
The figure is 580 and the SQL is
select sum(O.order_total) as revenue
from orders O
where O.order_date between '2026-03-01' and '2026-03-31'
The order_lines is irrelevant in this case unless you wanted revenue by product in which case you would use
select product, sum(item_price) as revenue
from orders O
join order_items OI on OI.order_id = O.order_id
where O.order_date between '2026-03-01' and '2026-03-31'
group by product
1
u/shah-26 Oct 31 '26
Thanks everyone! The answer is 580, and you're right that the items table isn't needed here, so my puzzle didn't force the join. My mistake.
The pitfall I was after: if you do join orders to order_items and then SUM(order_total), each order is counted once per item, which gives 1,620 here.
For people still learning: did you ever get caught by that? I'm trying to understand which SQL mistakes are most common when you're starting out, and whether feedback that explains why a total is wrong would have helped. I'll post a harder version where the join is needed.
1
u/Wonderful-Mode-4027 Oct 29 '26
The query is a simple SELECT SUM(order_total) FROM orders WHERE order_date BETWEEN 2026-03-01 AND 2026-03-31. Joining with order_items causes double counting because one order has multiple items.
1
u/woahboooom Oct 29 '26
Select #2026-03-01# month_date, sum(order_items.item_price) total_price From Orders left join order_items On orders.order_id = order_items.order_id Where orders.order_date >= #2026-03-01# and orders.order_date<#2026-04-01#