Sub topic 9
Generating every combination of two lists
This chapter assumes you know INNER JOIN and LEFT JOIN, can write basic SELECT, WHERE, and ORDER BY queries, and have seen that CROSS JOIN returns the Cartesian product of two tables. Here you will use that product on purpose. You will generate product variants, extend the idea to three lists, load the result into a table, and handle the edge cases that cause surprises.
The idea: one row for every pairing
A cross join has no ON condition. Each row from the left table is paired with each row from the right table. If you treat two tables as two lists, the result is every possible choice of one item from each list.
This is useful when the combinations are real things you need to store or report. Examples are the size and color variants of a shirt, the test cases for two configuration options, or the rows of a report grid.
The setup below creates the two lists and generates all combinations.
CREATE TABLE sizes (size VARCHAR(2));
CREATE TABLE colors (color VARCHAR(10));
INSERT INTO sizes (size) VALUES ('S'), ('M'), ('L');
INSERT INTO colors (color) VALUES ('red'), ('blue');
SELECT s.size, c.color
FROM sizes s
CROSS JOIN colors c
ORDER BY c.color, s.size;The result has 3 × 2 = 6 rows:
| size | color |
|---|---|
| L | blue |
| M | blue |
| S | blue |
| L | red |
| M | red |
| S | red |
SQL does not guarantee row order without ORDER BY. Always sort when you show combinations to people or compare output in a test. The sort here is alphabetical, which is why L comes before M and S. If you need a business order such as S, M, L, store a sort_order column and sort by it.
Predicting the row count
The row count of a cross join is the product of the input row counts. The formula is the same however many lists you combine.
| Left rows | Right rows | Result rows |
|---|---|---|
| 3 | 2 | 6 |
| 10 | 10 | 100 |
| 1,000 | 1,000 | 1,000,000 |
| 50,000 | 20,000 | 1,000,000,000 |
Check your prediction before you run an unfamiliar cross join. A quick way is to multiply two counts:
SELECT (SELECT COUNT(*) FROM sizes) * (SELECT COUNT(*) FROM colors) AS expected_rows;This returns 6, and it costs almost nothing compared with generating the rows.
Combining more than two lists
You can chain CROSS JOIN clauses. Each additional table multiplies the row count again. Add a third list of fabrics:
CREATE TABLE fabrics (fabric VARCHAR(10));
INSERT INTO fabrics (fabric) VALUES ('cotton'), ('wool');
SELECT s.size, c.color, f.fabric
FROM sizes s
CROSS JOIN colors c
CROSS JOIN fabrics f
ORDER BY f.fabric, c.color, s.size;The result has 3 × 2 × 2 = 12 rows. The order of the CROSS JOIN clauses does not change which rows appear, because multiplication is commutative. It only changes the default column order if you use SELECT *. Name your columns explicitly so the output does not depend on join order.
Saving the combinations with INSERT ... SELECT
Often you want the generated rows stored in a table, for example a variants table that other tables reference. INSERT ... SELECT writes the cross join result directly:
CREATE TABLE variants (
sku VARCHAR(20) PRIMARY KEY,
size VARCHAR(2) NOT NULL,
color VARCHAR(10) NOT NULL,
UNIQUE (size, color)
);
INSERT INTO variants (sku, size, color)
SELECT CONCAT(s.size, '-', UPPER(c.color)), s.size, c.color
FROM sizes s
CROSS JOIN colors c;This inserts six rows with SKUs such as S-RED and L-BLUE. The UNIQUE (size, color) constraint protects you from storing the same combination twice.
That constraint matters when the lists change. Suppose the business adds a color:
INSERT INTO colors (color) VALUES ('green');Running the earlier INSERT ... SELECT again would fail on the duplicate SKUs. Generate only the combinations that are missing instead:
INSERT INTO variants (sku, size, color)
SELECT CONCAT(s.size, '-', UPPER(c.color)), s.size, c.color
FROM sizes s
CROSS JOIN colors c
WHERE NOT EXISTS (
SELECT 1
FROM variants v
WHERE v.size = s.size
AND v.color = c.color
);This adds three rows (S, M, and L in green), for nine variants in total. You can run it repeatedly, and it does nothing once every combination exists.
Removing combinations you do not want
A WHERE clause on a cross join removes unwanted pairs. Suppose blue is not made in size L:
SELECT s.size, c.color
FROM sizes s
CROSS JOIN colors c
WHERE NOT (s.size = 'L' AND c.color = 'blue')
ORDER BY c.color, s.size;For two or three exclusions this is fine. For a long or changing list, store the exclusions in their own table and anti-join against it with NOT EXISTS, as in the previous section. The rules then live in data rather than in query text.
A cross join filtered by a condition that relates the two tables behaves like an inner join. These two queries return the same rows:
SELECT s.size, c.color
FROM sizes s
CROSS JOIN colors c
WHERE s.size = 'M';
SELECT s.size, c.color
FROM sizes s
INNER JOIN colors c ON s.size = 'M';Prefer CROSS JOIN when you mean "all pairs" and ON when the condition links the tables. The query then states your intent.
Edge cases that change the count
Empty lists
If either table has zero rows, the result has zero rows, because 3 × 0 = 0. This can look like a bug when a lookup table was never loaded. If a generated report suddenly returns nothing, count the rows in each input first.
Duplicate values
Duplicates in an input multiply through the result. If a list holds M twice, every color appears twice with M. Remove duplicates before the join, using a derived table:
SELECT s.size, c.color
FROM (
SELECT DISTINCT size
FROM (
SELECT 'S' AS size
UNION ALL SELECT 'M'
UNION ALL SELECT 'M'
) raw_sizes
) s
CROSS JOIN colors c;Without DISTINCT the same query returns 3 × 2 rows (six). With it, the two distinct sizes give four rows when colors holds red and blue. After you add green, the count becomes six.
This example also shows an inline list built with UNION ALL, which works without creating a table. On Oracle, each SELECT of a literal needs FROM dual. Some databases also accept VALUES lists as derived tables, but the syntax differs between systems.
NULL values
A NULL in a list is a row like any other. It pairs with every row on the other side, and the result contains NULL in that column. Filter with WHERE size IS NOT NULL inside the input if you do not want it.
Generating numbers from digits
A cross join can build sequences from a small table. Ten digits crossed with ten digits give the numbers 0 to 99:
CREATE TABLE digits (d INT PRIMARY KEY);
INSERT INTO digits (d) VALUES (0), (1), (2), (3), (4), (5), (6), (7), (8), (9);
SELECT tens.d * 10 + ones.d AS n
FROM digits tens
CROSS JOIN digits ones
ORDER BY n;The same digits table appears twice, so the aliases tens and ones are required, just as in a self join. Add a third CROSS JOIN for hundreds and you get 0 to 999. Many databases have a built-in series generator, such as generate_series in PostgreSQL. This technique is the portable fallback.
Common mistakes
- Forgetting that lists are multiplied, not matched. If you expected 3 rows and got 6, you wanted a join with a condition, not a cross join.
- Selecting
*and relying on column order. Name the columns you need. - Skipping the uniqueness constraint on stored combinations. Without it, rerunning a generation script silently doubles your data.
- Running a large cross join without checking input sizes. Multiply the counts first.
Exercise
The tables sizes (3 rows), colors (4 rows), and fabrics (2 rows) all have unique values. How many rows does FROM sizes CROSS JOIN colors CROSS JOIN fabrics return, and what happens to that count if fabrics is empty?
Show answer
It returns 3 × 4 × 2 = 24 rows. If fabrics is empty, the result has 0 rows, because any number multiplied by 0 is 0.
Exercise
Write a query that generates every combination of sizes and colors that does not already exist in the variants table, without using NOT EXISTS. Which join pattern do you use?
Show answer
Cross join the two lists, then LEFT JOIN variants on both columns and keep rows where the variants key is NULL:
SELECT s.size, c.color
FROM sizes s
CROSS JOIN colors c
LEFT JOIN variants v
ON v.size = s.size
AND v.color = c.color
WHERE v.sku IS NULL;
The LEFT JOIN marks existing combinations with a non-NULL sku, so the IS NULL filter leaves only the missing ones.