Why it happens: JOIN repeats rows
Orders 101 and 106 are two separate orders, but between them they have five order lines:
SELECT p.id AS order_id,
c.name AS customer,
dp.product_id
FROM orders AS p
JOIN customers AS c
ON c.id = p.customer_id
JOIN order_items AS dp
ON dp.order_id = p.id
WHERE p.id IN (101, 106)
ORDER BY p.id, dp.id;| order_id | customer | product_id |
|---|---|---|
| 101 | Amy Wilson | 1 |
| 101 | Amy Wilson | 2 |
| 101 | Amy Wilson | 5 |
| 106 | Sara Green | 4 |
| 106 | Sara Green | 8 |
The result is correct if you want one row per order line. It is only wrong if you meant one row per order.
How to fix it in SQL
If you want one row per order, aggregate the lines
SELECT p.id AS order_id,
c.name AS customer,
SUM(dp.quantity * dp.unit_price) AS lines_total
FROM orders AS p
JOIN customers AS c
ON c.id = p.customer_id
JOIN order_items AS dp
ON dp.order_id = p.id
WHERE p.id IN (101, 106)
GROUP BY p.id, c.name
ORDER BY p.id;| order_id | customer | lines_total |
|---|---|---|
| 101 | Amy Wilson | 128,40 |
| 106 | Sara Green | 1088,00 |
If you only want to know whether a match exists, you do not need to bring in every
In some problems, EXISTS expresses the intent better than joining a table just to check for presence, and it avoids pulling several rows from the dependent table into the main result.
How to check it
Count the matches for each key and confirm whether you want one row per order or one per line.
How to avoid it next time
DISTINCT can hide a bad join and does not fix a multiplied sum.
Related cases worth checking
Adding DISTINCT without diagnosing the relationship
DISTINCT removes rows that are identical across the selected columns. It can hide a multiplication, but it does not change the cardinality of the relationship. If you later add a detail column, the rows become different again. Decide first what one row represents.