SQL error · Extra rows appear

JOIN repeats rows

Problem: A row has several matches on the right, or the ON condition is incomplete.

Solution: Complete the JOIN key, aggregate to the level you need, or use EXISTS if you only want to test for existence.

Why it happens: JOIN repeats rows

Orders 101 and 106 are two separate orders, but between them they have five order lines:

SQL
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;
Verified result: one row per order line
order_idcustomerproduct_id
101Amy Wilson1
101Amy Wilson2
101Amy Wilson5
106Sara Green4
106Sara Green8

The result is correct if you want one row per order line. It is only wrong if you meant one row per order.

What the problem looks like

No error appears: the JOIN returns more rows than expected and the sums come out inflated.

Since the engine gives no warning, count the rows of the main table before and after the join: if they increase, some row has several matches.

How to fix it in SQL

If you want one row per order, aggregate the lines

One row per order
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;
Corrected granularity: one row per order
order_idcustomerlines_total
101Amy Wilson128,40
106Sara Green1088,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.