Sub topic 12
Cross Joins and Cartesian Products
This chapter assumes you can already write an INNER JOIN ... ON query and read the comma syntax with a join condition in WHERE. It also assumes you know table aliases and how NULL behaves. Here you will learn what a cross join is, why a missing join condition produces one by accident, how to detect that mistake, and when a cross join is the right tool.
What a Cartesian product is
A Cartesian product pairs every row of one table with every row of another. If table A has 3 rows and table B has 4 rows, the result has 3 × 4 = 12 rows. No condition decides which rows belong together, so every combination appears.
Every join starts conceptually from this product. A join condition then keeps only the pairs that satisfy it. An inner join on department_id is a Cartesian product followed by a filter. The optimizer does not build the full product first, but the result is defined as if it did. This is why forgetting the condition is so damaging: the filter that was supposed to reduce the rows is simply missing.
Writing a cross join on purpose
ANSI syntax has an explicit keyword for the product. It takes no ON and no USING clause.
SELECT e.last_name, d.department_name
FROM employees e
CROSS JOIN departments d;In the standard Oracle HR sample schema, employees has 107 rows and departments has 27. This query returns 107 × 27 = 2,889 rows. If your copy of the data differs, the result is still the product of the two row counts.
The comma syntax produces the same result when you leave out the WHERE condition:
SELECT e.last_name, d.department_name
FROM employees e, departments d;The two queries are equivalent, but they communicate different intent. CROSS JOIN says "I want the product." The comma form with no condition might be the same intent, or it might be a bug. A reader cannot tell. That is the main reason to write CROSS JOIN whenever you want the product.
| Form | Result | Intent visible? |
|---|---|---|
| `A CROSS JOIN B` | Every pair | Yes |
| `FROM A, B` with no join condition | Every pair | No, could be a mistake |
| `A JOIN B ON 1 = 1` | Every pair | Partly, the always-true condition is a signal |
| `A JOIN B` with no `ON` | Error (ORA-00905, missing keyword) | Not applicable |
The last row is a safety feature of ANSI syntax. With INNER JOIN, Oracle refuses to run the statement unless you supply ON or USING. Likewise, CROSS JOIN ... ON ... is a syntax error. The comma syntax has no such guard.
How accidental Cartesian products happen
An accidental product has one of a few common causes.
- The
WHEREcondition is forgotten in a comma-syntax query. - A multi-table query has too few join conditions. Joining N tables needs at least N − 1 conditions linking them.
- A condition does not link the two tables. An example is
e.department_id = e.department_id, which is true for every row with a non-null value and relates nothing. - An alias is mistyped so a condition refers to the wrong table.
The third case is the hardest to see, because the query contains a condition and looks complete. The condition links a table to itself rather than to its partner.
The multi-table case is the most common. Here a developer joins three tables but writes only one link:
SELECT e.last_name, d.department_name, l.city
FROM employees e, departments d, locations l
WHERE e.department_id = d.department_id;employees and departments are joined correctly. locations has no condition at all, so each joined row is paired with every row of locations. The result is the inner join count multiplied by the number of locations. Every employee appears once per city, and the city column is meaningless.
The fixed version adds the missing link:
SELECT e.last_name, d.department_name, l.city
FROM employees e, departments d, locations l
WHERE e.department_id = d.department_id
AND d.location_id = l.location_id;The same mistake in ANSI syntax is hard to make, because each JOIN requires its own ON. You can still write a wrong ON clause, but you cannot leave one out.
Spotting a Cartesian product
You can detect an accidental product in three ways.
Compare row counts. If a query on employees and departments returns far more rows than employees has, you likely have a product. For a many-to-one join, the result should not exceed the row count of the "many" side.
Look for repeated values. If every employee name appears dozens of times with different departments or cities, the join is missing a condition.
Read the execution plan. Oracle shows a Cartesian join as MERGE JOIN CARTESIAN in the plan:
EXPLAIN PLAN FOR
SELECT e.last_name, d.department_name, l.city
FROM employees e, departments d, locations l
WHERE e.department_id = d.department_id;
SELECT * FROM TABLE(DBMS_XPLAN.DISPLAY);Look for the MERGE JOIN CARTESIAN operation in the output. Its presence is a prompt to check your conditions. It is not always an error, because the optimizer sometimes chooses a Cartesian join between a very small table (such as one with a single row) and another table, even when the query has a proper condition. Treat it as a warning to read the query again, not as proof of a mistake.
When a cross join is the right tool
Intentional cross joins are less common than inner joins, but they have clear uses.
- Generating combinations, such as every product with every size, or every store with every month.
- Building a complete grid so that combinations with no data still appear, then outer joining the real data to the grid.
- Attaching a single-row value to every row, such as a parameter or a total from a one-row inline view.
The second use is the most valuable. Suppose you want the number of hires per department per year, including zero counts. A plain join with GROUP BY only shows combinations that have data. Instead, build the full grid of departments and years, then outer join the employees onto it:
SELECT d.department_id,
d.department_name,
y.yr,
COUNT(e.employee_id) AS hires
FROM departments d
CROSS JOIN (SELECT 2004 + LEVEL AS yr
FROM dual
CONNECT BY LEVEL <= 3) y
LEFT OUTER JOIN employees e
ON e.department_id = d.department_id
AND EXTRACT(YEAR FROM e.hire_date) = y.yr
GROUP BY d.department_id, d.department_name, y.yr
ORDER BY d.department_id, y.yr;The inline view y produces the years 2005, 2006 and 2007 using a row generator: CONNECT BY LEVEL <= 3 on dual returns three rows, and LEVEL supplies the numbers 1 to 3. The cross join pairs every department with every year. The LEFT OUTER JOIN then attaches matching employees. Because the year test sits in ON, not in WHERE, a department-year pair with no hires survives with NULL employee columns. COUNT(e.employee_id) counts only non-null values, so those pairs report 0. This depends on the rule from the chapter on ON versus WHERE: a filter on the outer table in WHERE would remove the zero rows.
The row generator also works alone. This small example is a quick way to see a product in action:
SELECT a.n AS a_value, b.n AS b_value
FROM (SELECT LEVEL AS n FROM dual CONNECT BY LEVEL <= 3) a
CROSS JOIN
(SELECT LEVEL AS n FROM dual CONNECT BY LEVEL <= 4) b
ORDER BY a.n, b.n;It returns 12 rows, from (1,1) through (3,4).
Cross joins by another route: NATURAL JOIN
A NATURAL JOIN joins on all columns that share a name in both tables. If the two tables have no column names in common, there is nothing to join on, and Oracle returns the Cartesian product instead of raising an error. A query that works today can therefore turn into a product after a column rename, with no warning. This is one of several reasons that explicit ON clauses are safer than NATURAL JOIN.
Cross joins and outer joins in the (+) syntax
Comma syntax with (+) still needs a real condition on every table pair. If you write an outer join marker but forget to link one of the tables, you still get a product for that table. The (+) operator does not protect against it. In ANSI syntax, an omitted ON is a syntax error, so the problem cannot go unnoticed.
Summary of rules
- A cross join returns m × n rows: every row of one table paired with every row of the other.
- Write
CROSS JOINwhen you want the product, so the intent is clear. - A comma-separated
FROMlist with a missing condition silently produces a product. - Joining N tables needs at least N − 1 linking conditions, and each must relate two different tables.
- Check for unexpectedly large row counts, repeated values, and
MERGE JOIN CARTESIANin the plan. - Use a cross join with an outer join to build a complete grid and show zero counts.
Exercise
A query joins employees, departments and locations with FROM employees e, departments d, locations l and the single condition WHERE e.departmentid = d.departmentid. Employees has 107 rows, of which 106 have a department, and locations has 23 rows. About how many rows does the query return, and what is the fix?
Show answer
Each of the 106 matching employee-department pairs is paired with all 23 locations, so the query returns 106 × 23 = 2,438 rows. The fix is to add the missing link between departments and locations: AND d.locationid = l.locationid. That brings the result back to one row per employee that has a department.
Exercise
Write a query that returns every combination of the numbers 1 to 2 and the letters 'X' and 'Y' (four rows), using CROSS JOIN and no existing tables other than dual.
Show answer
SELECT n.n, l.letter FROM (SELECT LEVEL AS n FROM dual CONNECT BY LEVEL <= 2) n CROSS JOIN (SELECT 'X' AS letter FROM dual UNION ALL SELECT 'Y' FROM dual) l ORDER BY n.n, l.letter;
Exercise
Why does a statement such as SELECT FROM employees e JOIN departments d (with no ON or USING clause) fail, while SELECT FROM employees e, departments d runs and returns every pair?
Show answer
ANSI inner join syntax requires a join condition, so Oracle raises an error (ORA-00905, missing keyword) when ON or USING is absent. The comma syntax puts the condition in WHERE, which is optional, so omitting it is valid and gives a Cartesian product.