Sub topic 8
CROSS JOIN versus the comma syntax
This chapter assumes you can write INNER JOIN and LEFT JOIN with an ON condition, and that you know a cross join returns the Cartesian product of two tables: every row of one paired with every row of the other. Here the focus is on how you write that join, why the two common spellings are not equally safe, and which dialect details matter.
Two spellings of the same join
SQL has two ways to ask for a Cartesian product. You can name the join explicitly, or you can list the tables separated by commas.
The examples in this chapter use these tables. Run this setup once.
CREATE TABLE sizes (size VARCHAR(2));
CREATE TABLE colors (color VARCHAR(10));
CREATE TABLE prices (size VARCHAR(2), price INT);
INSERT INTO sizes (size) VALUES ('S'), ('M'), ('L');
INSERT INTO colors (color) VALUES ('red'), ('blue');
INSERT INTO prices (size, price) VALUES ('S', 10), ('M', 12), ('L', 14);These two queries return the same six rows.
-- Explicit: SQL-92 style
SELECT s.size, c.color
FROM sizes s
CROSS JOIN colors c
ORDER BY s.size, c.color;
-- Comma: SQL-89 style
SELECT s.size, c.color
FROM sizes s, colors c
ORDER BY s.size, c.color;Database engines treat them as the same operation. They parse both into the same logical plan, so neither is faster. The difference is in how easy the query is to read and how easily it breaks.
Where the comma syntax comes from
Before SQL-92, SQL had no JOIN keyword. You listed every table in FROM and put the matching conditions in WHERE:
SELECT e.name AS employee, m.name AS manager
FROM employees e, employees m
WHERE e.manager_id = m.id;This still works in every major database, and old code and tutorials are full of it. In this style, a comma plus a WHERE condition is an inner join, and a comma with no condition is a cross join.
The trouble is that the query text does not say which one you meant. If a WHERE condition goes missing, the query does not fail. It silently turns into a cross join. With CROSS JOIN written out, the reader knows the product is intended. With INNER JOIN ... ON, the database rejects a join that has no condition.
Comparing the options
| Spelling | Intent visible to reader | Missing condition causes | Notes |
|---|---|---|---|
| `a CROSS JOIN b` | Clear: a product is wanted | Not possible, there is no condition | Preferred for deliberate products |
| `a, b` | Unclear: could be a join with a lost `WHERE` | A silent product | Legacy style |
| `a INNER JOIN b ON 1 = 1` | Clear but roundabout | Not possible | Works where `CROSS JOIN` is unavailable |
| `a INNER JOIN b ON TRUE` | Clear but roundabout | Not possible | Not valid in SQL Server, which has no `TRUE` literal in conditions |
Syntax rules for CROSS JOIN
CROSS JOIN takes no ON or USING clause in standard SQL. This is invalid in PostgreSQL and SQL Server:
-- Error in PostgreSQL and SQL Server: CROSS JOIN does not accept ON
SELECT s.size, c.color
FROM sizes s
CROSS JOIN colors c ON s.size = 'S';If you want to limit the product, use WHERE:
SELECT s.size, c.color
FROM sizes s
CROSS JOIN colors c
WHERE s.size = 'S';This returns two rows. A cross join followed by a WHERE that compares columns from both tables is logically an inner join, and the optimizer normally plans it as one. Even so, write INNER JOIN ... ON when you mean a match, so the join condition sits next to the join.
MySQL is more lenient. It treats JOIN, INNER JOIN, and CROSS JOIN as equivalent, so an ON clause after CROSS JOIN is accepted there. Do not rely on this. The query would fail if you moved it to another database.
Chaining more than two tables
You can chain as many CROSS JOIN operators as you need. The row counts multiply.
CREATE TABLE styles (style VARCHAR(10));
INSERT INTO styles (style) VALUES ('plain'), ('striped');
SELECT s.size, c.color, t.style
FROM sizes s
CROSS JOIN colors c
CROSS JOIN styles t
ORDER BY s.size, c.color, t.style;The result has 3 × 2 × 2 = 12 rows. The comma version, FROM sizes s, colors c, styles t, returns the same rows. With a long list of commas, though, it becomes harder to see which tables are meant to be matched and which are meant to be multiplied.
The precedence trap: mixing commas and JOIN
The most useful reason to prefer CROSS JOIN is an operator precedence rule. In a FROM clause, JOIN binds more tightly than the comma. The comma has the lowest precedence of all.
Suppose you want every size and color pair, with the price for each size. This looks reasonable:
-- Fails: the ON clause cannot see "sizes"
SELECT s.size, c.color, p.price
FROM sizes s, colors c
INNER JOIN prices p ON p.size = s.size;The database reads it as sizes s, (colors c INNER JOIN prices p ON p.size = s.size). The ON condition belongs to the join between colors and prices, and sizes is not part of that join. PostgreSQL rejects the query with an error that says the table entry for s cannot be referenced from this part of the query. MySQL reports an unknown column s.size in the on clause. The exact wording differs by database, but the cause is the same.
The fix is to use explicit joins throughout, which makes the order of evaluation match the order you read:
SELECT s.size, c.color, p.price
FROM sizes s
CROSS JOIN colors c
INNER JOIN prices p ON p.size = s.size
ORDER BY s.size, c.color;This returns six rows, one per size and color pair, each with the price for its size.
Reordering the tables also hides the problem. FROM colors c, sizes s INNER JOIN prices p ON p.size = s.size is valid, because sizes and prices are now adjacent. That is exactly why the bug appears and disappears when someone edits the FROM list. Explicit joins remove the dependency on table order.
Edge cases worth knowing
An empty table produces an empty result
A product of n rows and 0 rows has n × 0 = 0 rows. If one input table is empty, the whole cross join is empty:
CREATE TABLE promos (code VARCHAR(10));
SELECT s.size, p.code
FROM sizes s
CROSS JOIN promos p;This query returns zero rows, even though sizes has three. The same happens with the comma syntax.
If you want to keep the left rows even when the right table is empty, use a LEFT JOIN with a condition that is always true:
SELECT s.size, p.code
FROM sizes s
LEFT JOIN promos p ON 1 = 1
ORDER BY s.size;This returns three rows, each with a NULL code. When promos has rows, the query behaves like a cross join. This pattern is useful for optional lookup tables, such as a settings table that might be empty.
Duplicate rows multiply too
A cross join does not remove duplicates. If colors contained red twice, every size would appear with red twice, and the result would have 3 × 3 = 9 rows. Check the inputs with SELECT DISTINCT or a unique constraint if you need each combination once.
Column name clashes
When both tables have a column with the same name, an unqualified reference in SELECT or WHERE is ambiguous and the database raises an error. Always qualify with the alias, as in s.size. Both sizes and prices have a size column, so SELECT size FROM sizes s CROSS JOIN prices p fails.
Which should you use?
- Use
CROSS JOINwhen you want a product. It says so in the query text. - Use
INNER JOIN ... ONwhen you want matching rows, even if you could express the match inWHERE. - Keep the comma syntax for reading old code. If you meet it, check whether each pair of tables has a matching condition in
WHERE. - In SQL Server and other databases without a
TRUEliteral, useON 1 = 1for the always-true join condition.
Spotting a missing WHERE condition in comma-style queries is the subject of a later chapter, which covers accidental Cartesian products in more detail.
Exercise
A colleague writes SELECT s.size, c.color, p.price FROM sizes s, colors c INNER JOIN prices p ON p.size = s.size; and the database reports an error about s. Explain why it fails and rewrite the query so that it returns 6 rows.
Show answer
JOIN binds more tightly than the comma, so the ON condition is attached to the join of colors and prices, where the alias s is not visible. Rewrite with explicit joins: SELECT s.size, c.color, p.price FROM sizes s CROSS JOIN colors c INNER JOIN prices p ON p.size = s.size; This returns 6 rows, one for each size and color pair.
Exercise
The tables sizes (3 rows), colors (2 rows), and styles (2 rows) are combined with FROM sizes, colors, styles. How many rows come back? How many rows come back if colors is empty, and what query keeps the sizes rows in that case?
Show answer
3 x 2 x 2 = 12 rows. If colors is empty, the result has 0 rows because the product with an empty table is empty. To keep the sizes rows, use a LEFT JOIN with an always-true condition, such as SELECT s.size, c.color FROM sizes s LEFT JOIN colors c ON 1 = 1; each size then appears once with a NULL color.