Why a SQL LEFT JOIN produces duplicate rows, and how to fix it

By StringClass · Published

A LEFT JOIN returns one row for every matching pair. If a customer has two orders, that customer can appear twice. Choose what one output row represents, then aggregate or test existence at that level.

Before you start: You can read SELECT, WHERE, and GROUP BY. All examples use SQLite-compatible SQL, synthetic records, and integer cents.

Try the SQL example

Run a read-only query against the sample tables below. Compare the inflated and corrected totals, or edit the query yourself. Each run starts with the original sample data.

Use Tab to move between controls. Code runs in an isolated browser workspace. Edits stay on this page until you leave or reset it.

Ready to run

Run the example to see its output here.

Create the sample tables

Before fixing repeated rows, decide what one output row should represent. One row per customer, one per order, and one per returned item are three different reports. A join can be correct and still have the wrong shape for your intended report.

Run this setup once in a fresh SQLite database. Amounts are integer cents, and all records are synthetic.

CREATE TABLE customers (id INTEGER PRIMARY KEY, name TEXT NOT NULL);
CREATE TABLE orders (
  id INTEGER PRIMARY KEY,
  customer_id INTEGER NOT NULL,
  amount_cents INTEGER NOT NULL
);
CREATE TABLE returns (
  id INTEGER PRIMARY KEY,
  order_id INTEGER NOT NULL,
  amount_cents INTEGER NOT NULL
);

INSERT INTO customers VALUES (1, 'Ada'), (2, 'Bo'), (3, 'Cy');
INSERT INTO orders VALUES (10, 1, 1200), (11, 1, 800), (12, 2, 500);
INSERT INTO returns VALUES (100, 10, 200), (101, 10, 100);

Ada has two orders. One of those orders has two separate returns. Bo has one order and no returns. Cy has no orders. Those different counts are intentional: they reveal mistakes that one-order-per-customer sample data would hide.

See the matching pairs

SELECT c.id AS customer_id, c.name, o.id AS order_id
FROM customers AS c
LEFT JOIN orders AS o ON o.customer_id = c.id
ORDER BY c.id, o.id;
customer_id name order_id
1 Ada 10
1 Ada 11
2 Bo 12
3 Cy NULL

Ada appears twice because two orders match her ID. LEFT JOIN preserves Cy as an unmatched row, filling the order columns with NULL. It does not promise one result row per customer.

If you select only the customer name, Ada's two rows look identical. Adding IDs while debugging makes the different matching pairs visible. Avoid using names as join keys: names need not be unique.

Why totals become inflated

Adding another one-to-many relationship can repeat values you intended to sum only once:

SELECT c.id, c.name,
       SUM(o.amount_cents) AS ordered_cents,
       COALESCE(SUM(r.amount_cents), 0) AS returned_cents
FROM customers AS c
LEFT JOIN orders AS o ON o.customer_id = c.id
LEFT JOIN returns AS r ON r.order_id = o.id
GROUP BY c.id, c.name
ORDER BY c.id;

For Ada, order 10 now appears twice: once with return 100 and once with return 101. Her ordered total becomes 3200, although she ordered only 2000 cents. The 1200-cent order was counted twice. Grouping afterward cannot undo that repeated contribution.

SELECT DISTINCT removes identical output rows; it does not repair an already inflated sum. SUM(DISTINCT o.amount_cents) is also unsafe: two legitimate orders can have the same amount, and both should count.

Aggregate before joining

For this report, we want one row per customer with the total ordered and total returned. First reduce returns to one row per order. Then reduce orders to one row per customer. Finally join those customer totals to the customer list.

WITH return_totals AS (
  SELECT order_id, SUM(amount_cents) AS returned_cents
  FROM returns
  GROUP BY order_id
), customer_totals AS (
  SELECT o.customer_id,
         SUM(o.amount_cents) AS ordered_cents,
         SUM(COALESCE(r.returned_cents, 0)) AS returned_cents
  FROM orders AS o
  LEFT JOIN return_totals AS r ON r.order_id = o.id
  GROUP BY o.customer_id
)
SELECT c.id, c.name,
       COALESCE(t.ordered_cents, 0) AS ordered_cents,
       COALESCE(t.returned_cents, 0) AS returned_cents
FROM customers AS c
LEFT JOIN customer_totals AS t ON t.customer_id = c.id
ORDER BY c.id;
id name ordered_cents returned_cents
1 Ada 2000 300
2 Bo 500 0
3 Cy 0 0

The first grouped result has at most one row for each order_id. Joining it to orders cannot multiply an order by its number of returns. The second grouped result has at most one row per customer, matching the final report's shape.

COALESCE makes missing totals zero because that is the rule for this report. In other reports, a missing value may mean unknown rather than zero. Do not replace NULL automatically without deciding its meaning.

Use EXISTS for presence

Sometimes you only need customers who have at least one order. You do not need to carry order rows into the result:

SELECT c.id, c.name
FROM customers AS c
WHERE EXISTS (
  SELECT 1 FROM orders AS o WHERE o.customer_id = c.id
)
ORDER BY c.id;

This returns Ada and Bo once each. Cy is excluded. EXISTS answers a yes/no question for each customer rather than creating one result per matching order.

Also inspect right-table filters. WHERE o.amount_cents > 0 after a left join removes unmatched customers, because NULL does not pass that comparison. Put a restriction in the join's ON clause when you need to preserve customers without matching qualifying orders.

Check your understanding

Add another 1200-cent order for Ada, with no returns. The corrected report should show 3200 ordered cents and still 300 returned cents. A solution using SUM(DISTINCT amount_cents) will fail this check.

Then add a customer also named Ada with a different ID and no orders. The corrected report should retain a separate zero-total row. This checks that you group by identity rather than collapsing people who share a name.

The practical debugging sequence is: state the output row's meaning, inspect matching IDs, check how many right-hand rows each key can match, and aggregate at the required level. Indexes can improve execution, but they cannot correct a report's meaning. Use the database's query plan to assess performance rather than assuming every join has the same cost.

Reference: SQLite's SELECT documentation describes join processing, grouping, NULL-extended rows, and DISTINCT.