Sub topic 10
Spotting an accidental Cartesian product
This chapter assumes you can write INNER JOIN and LEFT JOIN with an ON condition, know primary and foreign keys, and understand how NULL behaves in comparisons. It also assumes you can use GROUP BY with COUNT and SUM. You have just seen that CROSS JOIN pairs every row of one input with every row of the other. Here you will learn how the same result appears by mistake, how to notice it, and how to fix it.
What an accidental Cartesian product is
A Cartesian product is the set of all pairings of rows from two inputs. A CROSS JOIN produces one on purpose. An accidental Cartesian product is the same result that you did not intend. The database does not warn you. It runs the query and returns a result that looks plausible on a small data set.
The row count of a full Cartesian product is the product of the input row counts. Two tables of 4 rows give 16 rows. Two tables of 10,000 rows give 100,000,000 rows. Mistakes that are invisible on test data become outages on production data.
Cause 1: a missing join condition
The most common cause is a join with no condition tying the two sides together. Here is the sample table from the self join chapters, so the examples below run on their own.
CREATE TABLE employees (
id INT PRIMARY KEY,
name VARCHAR(50) NOT NULL,
manager_id INT REFERENCES employees(id)
);
INSERT INTO employees (id, name, manager_id) VALUES
(1, 'Ava', NULL),
(2, 'Ben', 1),
(3, 'Chen', 1),
(4, 'Dana', 2);Suppose you want each employee with their manager, but you write the query like this:
SELECT e.name AS employee, m.name AS manager
FROM employees e
CROSS JOIN employees m;There is no relationship between e and m, so every employee is paired with every other employee, including themselves. The result has 4 × 4 = 16 rows. Ava appears as the manager of Dana, and Dana appears as the manager of Ava. The output looks like valid data, which is why this bug is easy to miss.
The correct query ties the two aliases together with the foreign key:
SELECT e.name AS employee, m.name AS manager
FROM employees e
INNER JOIN employees m ON e.manager_id = m.id;This returns 3 rows, because Ava has no manager.
Cause 2: the comma syntax and a forgotten WHERE
Older SQL lists tables separated by commas in the FROM clause and puts the join condition in WHERE.
SELECT e.name AS employee, m.name AS manager
FROM employees e, employees m
WHERE e.manager_id = m.id;This is valid and returns the correct 3 rows. If someone later edits the query and deletes or comments out the WHERE line, the query still runs and silently becomes a 16-row Cartesian product. With INNER JOIN ... ON, deleting the ON clause is a syntax error in most databases, so the mistake is caught immediately. This is the main reason to prefer explicit join syntax. A forgotten condition becomes an error instead of a wrong result.
The comma syntax has a second hazard. With three or more tables, you need one condition per join link. Missing a single link between two tables gives a Cartesian product between the two groups of tables.
-- Wrong: nothing links products to the other two tables
SELECT st.store_name, p.product_name, s.quantity
FROM stores st, products p, sales s
WHERE s.store_id = st.id;Here sales is linked to stores, but p is not linked to anything. Every sale is repeated once for every product.
Cause 3: an ON condition that does not connect the tables
A join can have an ON clause and still be a Cartesian product. This happens when the condition refers to only one side, usually from a copy-and-paste typo.
SELECT e.name AS employee, m.name AS manager
FROM employees e
INNER JOIN employees m ON e.manager_id = e.manager_id;The condition compares e.manager_id to itself. It never looks at m, so for each row of e where the condition is true, all rows of m match.
The result has 12 rows, not 16. The condition is true when manager_id is not NULL, and false when it is NULL, because NULL = NULL evaluates to unknown. Ben, Chen, and Dana each pair with all 4 rows of m. Ava is dropped. So you can get a partial Cartesian product: the row count is not a clean product of the table sizes, but it is still wrong.
A condition such as ON 1 = 1 or ON TRUE is a deliberate cross join. If you see it, check that the author meant it.
Cause 4: fan-out from two one-to-many joins
The previous causes involve a missing condition. This one has correct conditions, and it still multiplies rows. If you join a parent to two independent child tables, the children are paired with each other for each parent row.
CREATE TABLE skills (
employee_id INT REFERENCES employees(id),
skill VARCHAR(20)
);
CREATE TABLE projects (
employee_id INT REFERENCES employees(id),
project VARCHAR(20)
);
INSERT INTO skills (employee_id, skill) VALUES
(2, 'SQL'), (2, 'Python');
INSERT INTO projects (employee_id, project) VALUES
(2, 'Alpha'), (2, 'Beta'), (2, 'Gamma');Ben has 2 skills and 3 projects. Now count both in one query:
SELECT e.name,
COUNT(s.skill) AS skill_count,
COUNT(p.project) AS project_count
FROM employees e
INNER JOIN skills s ON s.employee_id = e.id
INNER JOIN projects p ON p.employee_id = e.id
GROUP BY e.id, e.name;Both counts come back as 6. Between the two child tables there is no link, so for Ben the database builds 2 × 3 = 6 combinations of skill and project. Each COUNT then counts the 6 rows. SUM would give inflated totals in the same way.
A quick fix is COUNT(DISTINCT s.skill). It works for counts of unique values, but not for SUM, because distinct values can legitimately repeat. The more reliable fix is to aggregate each child table down to one row per employee before joining:
SELECT e.name,
COALESCE(sk.skill_count, 0) AS skills_n,
COALESCE(pr.project_count, 0) AS projects_n
FROM employees e
LEFT JOIN (
SELECT employee_id, COUNT(*) AS skill_count
FROM skills
GROUP BY employee_id
) sk ON sk.employee_id = e.id
LEFT JOIN (
SELECT employee_id, COUNT(*) AS project_count
FROM projects
GROUP BY employee_id
) pr ON pr.employee_id = e.id
ORDER BY e.id;Each derived table has at most one row per employee, so no multiplication can occur. Ben shows 2 and 3, and the other employees show 0 and 0.
How to spot it
A Cartesian product leaves evidence. Check these signs in order.
- Compare row counts. Run
SELECT COUNT(*)on each input table, then on the join. If the join returns exactly the product of the input counts, the condition is missing. If it returns far more rows than either input, suspect fan-out. - Predict before you run. For a join from a child table to its parent on a foreign key, the result should have at most as many rows as the child table. If the result is larger, some join is not one-to-one.
- Look for repeated values. Scan the output for identical rows that differ only in one column, or for totals that are a multiple of what you expect.
- Read the join conditions. Every table in the
FROMclause should appear in at least one condition that also mentions a different table. - Check the plan.
EXPLAINoften shows a nested loop or a node labeled cross join or Cartesian join with no join filter. The exact wording depends on the database.
| Symptom | Likely cause | Check |
|---|---|---|
| Rows equal the product of input sizes | Missing or one-sided condition | Read each `ON` and `WHERE` |
| Query works after removing a `WHERE` line | Comma syntax without a link | Switch to `JOIN ... ON` |
| Totals are exact multiples of expected values | Fan-out from two one-to-many joins | Count rows per parent key |
| Query is slow and returns a huge result | Large inputs with no condition | Compare `COUNT(*)` to expected |
The flow below summarizes the diagnosis.
Fixing and preventing it
- Use
JOIN ... ONinstead of commas. A missingONis a syntax error in most databases, while a missingWHEREis silent. - Write
CROSS JOINwhen you mean it. The keyword tells readers the product is intentional. A cross join in a query that does not use it is a warning sign. - Qualify every column with its alias. A condition such as
e.manager_id = m.idmakes it easy to see that both sides are present. - Check uniqueness of join keys. If you expect a one-to-one match, verify it with
SELECT key, COUNT(*) FROM t GROUP BY key HAVING COUNT(*) > 1. Any rows returned are duplicate keys that multiply your result. - Aggregate before joining when two child tables hang off one parent.
- Test on small data first and compare the actual row count to your prediction.
Putting it together
The three self join and cross join queries you have seen in this tutorial look alike. A self join with ON e.manager_id = m.id returns 3 rows. The same query without the condition returns 16 rows. A cross join of sizes (3 rows) and colors (2 rows) returns 6 rows on purpose. The only difference between a correct join and a Cartesian product is the condition, so read it every time.
Exercise
The query SELECT e.name, m.name FROM employees e INNER JOIN employees m ON e.manager_id = e.manager_id; runs on the 4-row employees table from this chapter. How many rows does it return, and why is that not 16?
Show answer
It returns 12 rows. The condition compares e.managerid to itself and never uses m, so each row of e where the condition is true matches all 4 rows of m. The condition is true for Ben, Chen, and Dana, whose managerid is not NULL. For Ava, manager_id is NULL, and NULL = NULL is unknown, so her row is dropped. That gives 3 × 4 = 12 rows.
Exercise
A report joins employees to skills and to projects on employee_id, and then runs SUM(s.hours) and SUM(p.hours). Ben has 2 skill rows and 3 project rows, and the totals for Ben are too large. Explain the cause and give a fix.
Show answer
Skills and projects are independent one-to-many tables joined to the same employee, so Ben's 2 skill rows pair with his 3 project rows to give 6 joined rows. Each skill hours value is counted 3 times and each project hours value is counted 2 times. The fix is to aggregate each child table to one row per employee in a derived table (SELECT employeeid, SUM(hours) ... GROUP BY employeeid) and join those results to employees.
Exercise
Why is FROM a, b WHERE a.id = b.a_id riskier than FROM a INNER JOIN b ON a.id = b.a_id when the query is edited later?
Show answer
If someone removes the WHERE line, the comma version still runs and silently returns a Cartesian product. If someone removes the ON clause from the INNER JOIN version, most databases report a syntax error, so the mistake is caught immediately.