How would you design a SQL query to avoid the Cartesian product?

Instruction: Explain the potential issues with Cartesian products in SQL queries and how to design queries to avoid them.

Context: This question probes the candidate's understanding of the pitfalls in SQL query design, specifically the issue of Cartesian products, and their ability to write efficient queries.

Updated

Official answer

A Cartesian product pairs every row of one input with every row of another: inputs of m and n rows produce m×n rows. It can be intentional, such as generating every date/product combination, but an accidental missing join condition can produce incorrect totals and excessive work.

Use explicit relationships and verify their cardinality. For example:

SELECT e.employee_id, e.name, d.department_name
FROM employees AS e
JOIN departments AS d ON d.department_id = e.department_id
WHERE e.status = 'Active'
ORDER BY e.employee_id;

Assume departments.department_id is unique. An active employee matches at most one department; employees without a match are excluded by this inner join. Use a left join if those employees should remain.

An ON clause is not sufficient by itself: ON TRUE still forms all combinations, and a nonunique or incomplete key can multiply matches. Check missing parts of composite keys and compare expected row counts. Adding DISTINCT can hide a faulty join while losing legitimate rows. Subqueries and aliases improve structure or clarity but do not automatically prevent Cartesian products.

Related Questions