Sub topic 11
Reporting zeros: CROSS JOIN plus LEFT JOIN
This chapter assumes you can write INNER JOIN and LEFT JOIN with an ON condition, use GROUP BY with SUM, and handle NULL with COALESCE. It also assumes you know what a Cartesian product is from the earlier cross join chapters.
The problem: missing rows are not zeros
A report that groups sales by store and product only shows combinations that have at least one sale row. If the Downtown store never sold a kayak, no row says "Downtown, kayak, 0". The row is missing, and a reader cannot tell "zero sales" from "we forgot to check".
Grouping cannot fix this. GROUP BY summarizes rows that exist. To report a zero, you first need a row that represents the combination. Then you attach the sales to it.
The pattern has three steps:
- Use CROSS JOIN to build every combination you want to see. This is the complete list of rows the report should have.
- Use LEFT JOIN to attach the facts (sales) to each combination. Combinations without facts keep their row and get NULL columns.
- Use COALESCE around the aggregate to turn the resulting NULL or empty sum into 0.
Sample data
The examples use three small tables. The sales table records one row per sale event.
CREATE TABLE stores (
id INT PRIMARY KEY,
store_name VARCHAR(30) NOT NULL
);
CREATE TABLE products (
id INT PRIMARY KEY,
product_name VARCHAR(30) NOT NULL
);
CREATE TABLE sales (
id INT PRIMARY KEY,
store_id INT NOT NULL REFERENCES stores(id),
product_id INT NOT NULL REFERENCES products(id),
quantity INT NOT NULL
);
INSERT INTO stores (id, store_name) VALUES
(1, 'Downtown'),
(2, 'Airport');
INSERT INTO products (id, product_name) VALUES
(1, 'Kayak'),
(2, 'Paddle'),
(3, 'Helmet');
INSERT INTO sales (id, store_id, product_id, quantity) VALUES
(1, 1, 1, 2),
(2, 1, 1, 1),
(3, 1, 2, 5),
(4, 2, 2, 4);There are 2 stores and 3 products, so 6 store and product pairs are possible. The sales table covers only 3 of them: Downtown/Kayak, Downtown/Paddle and Airport/Paddle.
What a plain aggregate reports
Start with the ordinary grouped query.
SELECT st.store_name, p.product_name, SUM(s.quantity) AS total_quantity
FROM sales s
INNER JOIN stores st ON st.id = s.store_id
INNER JOIN products p ON p.id = s.product_id
GROUP BY st.id, st.store_name, p.id, p.product_name
ORDER BY st.id, p.id;It returns three rows:
| store_name | product_name | total_quantity |
|---|---|---|
| Downtown | Kayak | 3 |
| Downtown | Paddle | 5 |
| Airport | Paddle | 4 |
Downtown/Helmet, Airport/Kayak and Airport/Helmet are absent. Any chart or spreadsheet built on this output will have holes.
Step 1: build the grid with CROSS JOIN
Join the two dimension tables (stores and products) with no condition. Every store meets every product.
SELECT st.id AS store_id, st.store_name,
p.id AS product_id, p.product_name
FROM stores st
CROSS JOIN products p
ORDER BY st.id, p.id;This returns 2 × 3 = 6 rows. This grid is the skeleton of the report. Whatever happens next, these 6 rows must all appear in the output.
Step 2: attach the facts with LEFT JOIN
Now LEFT JOIN sales to the grid. The grid is on the left, so every grid row survives.
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
ORDER BY st.id, p.id;The result has all 6 rows:
| store_name | product_name | total_quantity |
|---|---|---|
| Downtown | Kayak | 3 |
| Downtown | Paddle | 5 |
| Downtown | Helmet | 0 |
| Airport | Kayak | 0 |
| Airport | Paddle | 4 |
| Airport | Helmet | 0 |
Two details make this work.
- The ON condition uses both keys. A sale matches a grid row only when the store and the product both agree. With only one key, each grid row would pick up sales of the wrong product or store.
- A grid row with no matching sale produces one joined row where every
scolumn is NULL.SUMover only NULL values returns NULL, andCOALESCE(..., 0)turns that into 0.
Common errors
Putting the sales filter in WHERE
Suppose you want only sales from 2026. The natural attempt adds a WHERE clause:
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
WHERE s.sold_on >= DATE '2026-01-01'
GROUP BY st.id, st.store_name, p.id, p.product_name;This assumes sales has a sold_on date column, which our sample table does not. The problem is the logic. For an unmatched grid row, s.sold_on is NULL, the comparison is not true, and WHERE discards the row. The zeros disappear, and the LEFT JOIN behaves like an INNER JOIN.
Move the condition into ON, so it restricts which sales match instead of which grid rows survive:
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
AND s.sold_on >= DATE '2026-01-01'
GROUP BY st.id, st.store_name, p.id, p.product_name;Using COUNT(*) instead of COUNT(column)
If you report the number of sales rows instead of a sum, the choice of COUNT matters. After the LEFT JOIN, a grid row with no sales still produces one joined row, so COUNT(*) returns 1 for it. COUNT(s.id) skips NULLs and returns 0, which is what you want.
SELECT st.store_name, p.product_name,
COUNT(s.id) AS sale_count
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
ORDER BY st.id, p.id;Count a column from the right-hand table, preferably its primary key, which is never NULL in a real row.
Duplicated rows in the grid
The grid is only as clean as its inputs. If products contained the same product twice, every store would get both copies and the totals would be doubled when both copies match the same sales. Keep dimension tables unique on the key you join with.
Fan-out from other joins
If you add a third table that has many rows per grid row, such as sale line items, and you also sum a column from the first fact table, sums multiply. Aggregate each fact table in its own subquery, then join the results to the grid.
The grid can come from any lists
The cross join does not need two tables. Any two row sources work: a table and a subquery, a small VALUES list, or a generated series of dates. A common case is a report with one row per store per month, including months with no sales. The calendar side of the cross join is often generated rather than stored.
The idea is always the same. Decide which rows the report must contain, build them with CROSS JOIN, and attach the facts with LEFT JOIN.
Relation to the earlier patterns
This chapter combines two ideas you have seen already. The LEFT self join kept employees with no manager. The grid plus LEFT JOIN keeps combinations with no sales. In both cases the left side defines the rows that must survive, and NULLs on the right mark the absence of a match.
Cost
The grid has rows(A) × rows(B) rows before the LEFT JOIN. With 500 stores and 2,000 products, that is 1,000,000 grid rows, and the join to sales must be checked for each. An index on sales(store_id, product_id) lets the database find matching sales quickly instead of scanning the table once per grid row. Decide first whether you really need every combination, or only those in a business-relevant subset such as active products per store.
Exercise
Using the sample tables, write a query that returns every store and product combination with the number of sale rows (not the quantity), showing 0 where there are none. Why would COUNT(*) give the wrong answer?
Show answer
SELECT st.storename, p.productname, COUNT(s.id) AS salecount FROM stores st CROSS JOIN products p LEFT JOIN sales s ON s.storeid = st.id AND s.productid = p.id GROUP BY st.id, st.storename, p.id, p.product_name ORDER BY st.id, p.id; COUNT(*) counts joined rows, and an unmatched grid row still produces one joined row with NULL sales columns, so it would report 1 instead of 0. COUNT(s.id) ignores the NULL and returns 0.
Exercise
A colleague adds WHERE s.quantity > 0 to the report query that uses CROSS JOIN and LEFT JOIN. The zero rows vanish. Explain why and describe the fix.
Show answer
For unmatched grid rows, s.quantity is NULL, so the condition s.quantity > 0 is not true and WHERE removes those rows. The LEFT JOIN then acts like an INNER JOIN. If the filter is meant to limit which sales are counted, move it into the ON clause (AND s.quantity > 0). If the goal is only to hide zero rows, filter after aggregation with HAVING instead.