// troubleshooting guide

Joins that multiply rows

A join that produces far more rows than it was given is either missing its join condition or fanning out across a one-to-many relationship. How both look in a plan, why DISTINCT only hides them, and the rewrites that remove the extra rows.

Covers PostgreSQL MySQL SQL Server Oracle

The symptom

Follow the row counts up a plan and they normally shrink or stay level. When a join outputs many more rows than its larger input, the query is multiplying rows. There are two causes. A join with no condition pairs every row of one input with every row of the other, a cartesian product. A join from a parent to a child table, or to two unrelated child tables at once, repeats each parent row once per child. Often a DISTINCT oder GROUP BY sits on top to collapse the duplicates again, so the result looks right while the work underneath is many times larger than needed.

das query plan viewer flags joins with no join predicate and joins whose output is collapsed again above them. The examples use a shop schema with 20,000 customers, 400,000 orders and 800,000 order items.

Diagnose it

A join with no join condition

This query lists two tables and filters each, but never says how they relate. 4,000 customers times 4,000 pending orders is 16 million rows:

EXPLAIN (COSTS OFF)
SELECT c.email, o.order_id
FROM customers AS c, orders AS o
WHERE c.country = 'DE' AND o.status = 'pending';
Nested Loop
  ->  Seq Scan on orders o
        Filter: ((status)::text = 'pending'::text)
  ->  Materialize
        ->  Seq Scan on customers c
              Filter: (country = 'DE'::bpchar)

In PostgreSQL the sign is a Nested Loop ohne Join Filter und kein Index Cond that refers to the other table. The other engines name the problem:

EXPLAIN FORMAT=TREE
SELECT c.email, o.order_id
FROM customers AS c, orders AS o
WHERE c.country = 'DE' AND o.status = 'pending';
-> Inner hash join (no condition)  (cost=8.21e+6 rows=8.03e+6)
    -> Filter: (o.`status` = 'pending')  (cost=87.7 rows=39864)
        -> Table scan on o  (cost=87.7 rows=398641)
    -> Hash
        -> Filter: (c.country = 'DE')  (cost=2040 rows=2015)
            -> Table scan on c  (cost=2040 rows=20154)
EXPLAIN PLAN FOR
SELECT c.email, o.order_id
FROM customers c, orders o
WHERE c.country = 'DE' AND o.status = 'pending';

SELECT * FROM TABLE(DBMS_XPLAN.DISPLAY);
| Id  | Operation            | Name      | Rows  | Bytes | Cost (%CPU)| Time     |
|   0 | SELECT STATEMENT     |           |    16M|   595M|   129K  (1)| 00:00:06 |
|   1 |  MERGE JOIN CARTESIAN|           |    16M|   595M|   129K  (1)| 00:00:06 |
|*  2 |   TABLE ACCESS FULL  | ORDERS    |  4000 | 56000 |   650   (1)| 00:00:01 |
|   3 |   BUFFER SORT        |           |  4000 |    97K|   128K  (1)| 00:00:06 |
|*  4 |    TABLE ACCESS FULL | CUSTOMERS |  4000 |    97K|    32   (0)| 00:00:01 |

SQL Server puts a warning on the join operator, shown as No Join Predicate in the graphical plan and as this element in the plan XML:

SET SHOWPLAN_XML ON;
GO
SELECT c.Email, o.OrderId
FROM dbo.Customers AS c, dbo.Orders AS o
WHERE c.Country = 'DE' AND o.Status = 'pending';
GO
SET SHOWPLAN_XML OFF;
<Warnings NoJoinPredicate="1" />

A fan-out that DISTINCT collapses again

Joining orders to their items returns one row per item. If the query only wants the orders, a DISTINCT has to remove the repeats:

EXPLAIN (ANALYZE, TIMING OFF, SUMMARY OFF, BUFFERS OFF)
SELECT DISTINCT o.order_id, o.total
FROM orders AS o
JOIN order_items AS i ON i.order_id = o.order_id
WHERE o.customer_id = 1;
HashAggregate  (cost=25348.89..25742.89 rows=39400 width=10) (actual rows=40000.00 loops=1)
  Group Key: o.order_id, o.total
  Batches: 1  Memory Usage: 2329kB
  ->  Gather  (cost=7770.55..24954.89 rows=78800 width=10) (actual rows=80000.00 loops=1)
        Workers Planned: 2
        Workers Launched: 2
        ->  Parallel Hash Join  (cost=6770.55..16074.89 rows=32833 width=10) (actual rows=26666.67 loops=3)
              Hash Cond: (i.order_id = o.order_id)
              ->  Parallel Seq Scan on order_items i  (cost=0.00..8429.33 rows=333333 width=4) (actual rows=266666.67 loops=3)
              ->  Parallel Hash  (cost=6565.33..6565.33 rows=16417 width=10) (actual rows=13333.33 loops=3)
                    Buckets: 65536  Batches: 1  Memory Usage: 2464kB
                    ->  Parallel Seq Scan on orders o  (cost=0.00..6565.33 rows=16417 width=10) (actual rows=13333.33 loops=3)
                          Filter: (customer_id = 1)
                          Rows Removed by Filter: 120000

Read the actual rows from the bottom up: 40,000 orders go into the join, 80,000 rows come out, and the HashAggregate at the top brings them back to 40,000. A join whose output is larger than its inputs, directly under an operator that removes duplicates, is the pattern.

Totals that come out too high

Without the DISTINCT, a fan-out makes aggregates wrong, not just slow. Each order's total is counted once per item:

SELECT count(*) AS order_rows, sum(o.total) AS revenue
FROM orders AS o
JOIN order_items AS i ON i.order_id = o.order_id
WHERE o.customer_id = 4242;

SELECT count(*) AS order_rows, sum(total) AS revenue
FROM orders
WHERE customer_id = 4242;
order_rows | revenue
        39 | 13824.70
order_rows | revenue
        20 | 7093.00

The customer has 20 orders. The joined query counts 39 rows and nearly doubles the revenue.

Fix it

Add the missing join condition

Write joins with JOIN ... ON so that a join without a condition is a syntax error instead of a slow query:

EXPLAIN (COSTS OFF)
SELECT c.email, o.order_id
FROM customers AS c
JOIN orders AS o ON o.customer_id = c.customer_id
WHERE c.country = 'DE' AND o.status = 'pending';
Gather
  Workers Planned: 2
  ->  Hash Join
        Hash Cond: (o.customer_id = c.customer_id)
        ->  Parallel Seq Scan on orders o
              Filter: ((status)::text = 'pending'::text)
        ->  Hash
              ->  Seq Scan on customers c
                    Filter: (country = 'DE'::bpchar)

In a query with many tables, check that every table is connected to the rest by at least one condition, and that composite keys are joined on all of their columns. Joining on half of a two-column key produces a smaller version of the same multiplication.

Use EXISTS when you only test for a match

If the query needs no columns from the child table, ask whether a matching row exists. The engine stops at the first match for each order and returns each order once, so there is nothing to de-duplicate:

EXPLAIN (ANALYZE, TIMING OFF, SUMMARY OFF, BUFFERS OFF)
SELECT o.order_id, o.total
FROM orders AS o
WHERE o.customer_id = 1
  AND EXISTS (SELECT 1 FROM order_items AS i WHERE i.order_id = o.order_id);
Gather  (cost=1000.42..21702.05 rows=34101 width=10) (actual rows=40000.00 loops=1)
  Workers Planned: 2
  Workers Launched: 2
  ->  Nested Loop Semi Join  (cost=0.42..17291.95 rows=14209 width=10) (actual rows=13333.33 loops=3)
        ->  Parallel Seq Scan on orders o  (cost=0.00..6565.33 rows=16417 width=10) (actual rows=13333.33 loops=3)
              Filter: (customer_id = 1)
              Rows Removed by Filter: 120000
        ->  Index Only Scan using order_items_pkey on order_items i  (cost=0.42..0.79 rows=2 width=4) (actual rows=1.00 loops=40000)
              Index Cond: (order_id = o.order_id)
              Heap Fetches: 0
              Index Searches: 40000

The plan now uses a semi join and its output is 40,000 rows, with no aggregate above it. The same rewrite works in every engine.

Aggregate the child rows before joining

When you do need numbers from the child table, reduce it to one row per parent first and then join. Each order appears once, so its total is counted once:

SELECT count(*) AS order_rows, sum(o.total) AS revenue, sum(i.item_count) AS items
FROM orders AS o
JOIN (
    SELECT order_id, count(*) AS item_count
    FROM order_items
    GROUP BY order_id
) AS i ON i.order_id = o.order_id
WHERE o.customer_id = 4242;
order_rows | revenue | items
        20 | 7093.00 |    39

The same applies when a parent is joined to two different child tables: aggregate each child separately, then join the results to the parent.

When to leave it alone

A cartesian product is correct when you mean it: pairing every date with every product to build a report grid, or joining to a table that holds a single row. Engines also choose a cartesian join on purpose when one input is known to be one row. And a join that returns more rows than its input is simply the answer when the query asks for the child rows. Act when the extra rows are thrown away again further up, or when the result is wrong.

The checklist

Work through it in order. Each step gives you the evidence for the next one.

  1. Follow actual row counts up the plan and find the join where they jump.
  2. Check that the join has a condition linking the two inputs.
  3. Check composite keys are joined on every column.
  4. Look above the join for DISTINCT or GROUP BY that collapses the rows again.
  5. Replace joins used only as an existence test with EXISTS.
  6. Aggregate child tables to one row per parent before joining them.
  7. Compare totals against a query on the parent table alone.

Questions that come up

What is a cartesian product in a query plan?

It is a join with no condition, so every row from one input is paired with every row from the other. Oracle labels it MERGE JOIN CARTESIAN, MySQL shows a join with no condition, SQL Server adds a No Join Predicate warning, and PostgreSQL shows a nested loop without a join filter.

Why does my join return duplicate rows?

Because the join follows a one-to-many relationship: each row on the one side is returned once for every matching row on the many side. If you only need the one side, use EXISTS. If you need figures from the many side, aggregate it to one row per key before joining.

Is SELECT DISTINCT a fix for duplicate rows from a join?

It hides them at a cost. The join still produces every duplicate, and the engine then has to sort or hash the whole result to remove them. It also does nothing for sums and counts computed before the DISTINCT. Removing the fan-out is cheaper and safer.

Why is my SUM too high after adding a join?

The new join repeats each row once per match, and the sum adds the repeated values. Compare the result with the same sum on the base table alone. Aggregate the joined table in a subquery first so that the join cannot multiply rows.

Does the old comma join syntax cause cartesian products?

Not by itself, but it makes them easy to write. With tables listed after FROM and conditions in WHERE, leaving out one condition still gives a valid query. With JOIN ... ON, every join has to state its condition.

// fix it where the query lives

Run these queries in SQLly

SQLly is a native SQL workbench for macOS, Windows and Linux. The query plan viewer and formatter these guides link to are built into its editor.