UPDATESQL

Unit 9, Checking AI-written SQL · Checking joins

Checking AI-written SQL: did a join multiply the rows?

Check the AI: delivered orders per customer

Joining a table to a table with several matching rows repeats each row once per match. One order with three items becomes three rows. Counts and sums over those rows come out too high, and nothing in the query looks wrong.

Example
SELECT o.id, COUNT(*) AS item_rows
FROM orders o
JOIN order_items oi ON oi.order_id = o.id
GROUP BY o.id;

Review the AI's query

Someone asked an AI assistant: How many delivered orders has each customer placed? Return customer_id and order_count for every customer with at least one delivered order. It wrote this query:

SELECT o.customer_id, COUNT(*) AS order_count
FROM orders o
JOIN order_items oi ON oi.order_id = o.id
WHERE o.status = 'delivered'
GROUP BY o.customer_id;

Does it answer the question?

  • Yes, it answers the question
  • No: it counts order lines, so orders with several items are counted more than once
  • No: it leaves out customers with only one order
Show the answer

No: it counts order lines, so orders with several items are counted more than once. Joining to order_items gives one row per item, so an order with three items is counted three times. The join is not needed for this question at all. This is the most common way AI-written SQL inflates a number.

Then fix it

Now fix the AI's query so each order is counted once.

Tables you will use: orders, order_items

Try it in your browserFree, no sign-up. Your query is checked as you go.