Sub topic 3
Generating Every Combination of Two Lists
This chapter assumes you know SELECT, WHERE, ORDER BY, INNER JOIN and LEFT JOIN with an ON condition, GROUP BY, SUM, and NULL handling.
Generating every combination of two lists
A CROSS JOIN pairs each row of the left table with each row of the right table. It has no ON condition. Three sizes and two colors produce 3 × 2 = 6 rows.
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 s.size, c.color;Spotting an accidental Cartesian product
Listing two tables after FROM with a comma, and leaving out the join condition, also creates a cross join. The row count grows quickly. A join of 1,000 orders with 1,000 customers returns 1,000,000 rows when the condition is missing.
-- Bug: no WHERE condition, so every order pairs with every customer
SELECT o.id, c.name
FROM orders o, customers c;Reporting zeros: CROSS JOIN plus LEFT JOIN
A CROSS JOIN builds every store and product pair. A LEFT JOIN then attaches sales to those pairs. COALESCE turns the NULL from a missing sale into 0. This example assumes stores(id, storename), products(id, productname), and sales(storeid, productid, quantity) tables.
SELECT st.store_name, p.product_name,
COALESCE(SUM(s.quantity), 0) AS total_quantity
FROM stores st
CROSS JOIN products p
LEFT JOIN sales s
ON s.store_id = st.id
AND s.product_id = p.id
GROUP BY st.id, st.store_name, p.id, p.product_name;Row growth, indexes, and checking your results
A cross join of n rows and m rows returns n × m rows. Three tables of 100 rows each produce 1,000,000 rows when joined in full. Index the columns used in ON conditions, such as sales.storeid and sales.productid, so the database can find matches quickly. Check results by comparing COUNT(*) with the expected product of the table sizes.
Beyond one level: recursive CTEs
Chaining many self joins becomes long when a hierarchy has many levels. A recursive CTE walks the hierarchy to any depth. The example below uses the employees table with id, name, and manager_id columns. SQL Server omits the RECURSIVE keyword.
WITH RECURSIVE chain AS (
SELECT id, name, manager_id, 0 AS depth
FROM employees
WHERE manager_id IS NULL
UNION ALL
SELECT e.id, e.name, e.manager_id, c.depth + 1
FROM employees e
INNER JOIN chain c ON e.manager_id = c.id
)
SELECT name, depth
FROM chain
ORDER BY depth, name;Exercise
How many rows does SELECT * FROM sizes s CROSS JOIN colors c return if sizes has 4 rows and colors has 5 rows?
Show answer
20 rows. A cross join returns 4 × 5 = 20 row pairs.