Asked for "revenue and number of orders that contain electronics, by customer segment", a text-to-SQL bot generated the query below. The Gold segment has exactly two orders: order 101 (total 80) has two electronics items, and order 102 (total 80) has one electronics item and one grocery item. What does the query return for Gold, and what is the right fix?
SELECT c.segment,
SUM(o.order_total) AS revenue,
COUNT(o.order_id) AS orders
FROM orders o
JOIN order_items i ON i.order_id = o.order_id
JOIN customers c ON c.customer_id = o.customer_id
WHERE i.category = 'Electronics'
GROUP BY c.segment;Show the answer and explanation
Correct answer: D, Revenue 240 and 3 orders: order 101 appears once per matching item; filter orders with EXISTS on order_items instead, so each order is joined only once.
Explanation Text-to-SQL
Joining to a one-to-many child table changes the grain of the result: one row per matching order item, not per order. An order-level column such as order_total is then repeated once per matching child row, and aggregates count it several times. This join fan-out is one of the most common silent errors in generated SQL, because the query runs and the numbers look plausible.
Rows after the joins and the WHERE filter:
| order_id | order_total | item category |
|---|---|---|
| 101 | 80 | Electronics |
| 101 | 80 | Electronics |
| 102 | 80 | Electronics |
So the query returns SUM = 240 and COUNT = 3, while the truth is 160 and 2. The grocery row is removed by WHERE, which always filters rows before GROUP BY. Filtering the items before the join, as optimizers often do, changes nothing: order 101 still matches two electronics rows.
Fix: keep the query at order grain and use the items table only as a filter:
SELECT c.segment, SUM(o.order_total) AS revenue, COUNT(*) AS orders
FROM orders o JOIN customers c ON c.customer_id = o.customer_id
WHERE EXISTS (SELECT 1 FROM order_items i
WHERE i.order_id = o.order_id AND i.category = 'Electronics')
GROUP BY c.segment;COUNT(DISTINCT o.order_id) would fix the count, but SUM(DISTINCT o.order_total) is a trap: it adds each distinct value once, so the two orders of 80 sum to 80 instead of 160.
Interview tip: for text-to-SQL, describe each table's grain in the schema prompt, add few-shot examples that aggregate before joining or use EXISTS, and test with questions whose answers you already know.