LEFT JOIN and zeros
Tasks often say “for every product” or “include merchants with no sales”. An inner join, or a filter in the wrong place, drops the zeros. The report then looks complete while rows are missing. The recipe has five steps, and each step prevents a known mistake.
Start from the table of all X
Section titled “Start from the table of all X”LEFT JOIN keeps every row of the left table. A left row without a match gets one row with NULL in every column of the right table. So the table that holds all X goes on the left.
An example: every merchant with the marketplace payouts for August sales. Some payouts have not arrived yet.
SELECT m.id, COUNT(cp.payout_id) AS payouts, COALESCE(SUM(cp.amount_usd), 0) AS paid_usdFROM merchants mLEFT JOIN channel_payouts cp ON cp.merchant_id = m.id AND cp.period_month = DATE '2026-08-01'GROUP BY m.idORDER BY m.id;The first three of 12 rows:
| id | payouts | paid_usd |
|---|---|---|
| mer_01 | 0 | 0 |
| mer_02 | 1 | 154.57 |
| mer_03 | 1 | 89.20 |
There is one row per merchant, and mer_01 and mer_11 show 0. An inner JOIN would return only 10 merchants. The two without a payout, which are the point of the report, would be gone.
Here is what the join produces before grouping, for two merchants:
SELECT m.id, cp.payout_id, cp.channel, cp.amount_usdFROM merchants mLEFT JOIN channel_payouts cp ON cp.merchant_id = m.id AND cp.period_month = DATE '2026-08-01'WHERE m.id IN ('mer_01', 'mer_02')ORDER BY m.id;| id | payout_id | channel | amount_usd |
|---|---|---|---|
| mer_01 | NULL | NULL | NULL |
| mer_02 | po_0026 | south_market | 154.57 |
mer_01 has no payout for August, so it gets one row of NULLs. The next three rules all come from this row.
Conditions on the right table go in ON
Section titled “Conditions on the right table go in ON”ON is applied while rows are matched; WHERE is applied after the join. A condition on the right table in WHERE is NULL for the row of NULLs, so WHERE drops that row, and the LEFT JOIN behaves like an inner join. In the query above, moving cp.period_month = DATE '2026-08-01' from ON to WHERE returns 10 rows: mer_01 and mer_11 disappear.
Sales in Japan in September for each product, 'including zeros'. How many of the 20 products will be in the result?
Guess the result first, then run the query. Fix the query, then Check.
Output columns: products_in_result
Tables, columns and how they connect
products — products (20 rows); a merchant can own several
id— key: prd_01 …
| id |
|---|
| prd_01 |
| prd_02 |
| prd_03 |
transactions — one row = one paid (or trial) period of a subscription
product_id— → products.idstart_time— start of the period = time of purchase; "started in …" means this columncountry— customer's country
| product_id | start_time | country |
|---|---|---|
| prd_01 | 2025-01-05 05:52:57 | IN |
| prd_01 | 2025-01-03 05:03:11 | BR |
| prd_01 | 2025-01-10 11:02:39 | JP |
Joins: transactions.product_id = products.id
"Today" is 2026-09-30 00:00 UTC. All times are UTC. Every run is rolled back, so you cannot break the data.
SELECT COUNT(*) AS products_in_result
FROM (
SELECT p.id, COUNT(t.product_id) AS sales
FROM products p
LEFT JOIN transactions t ON t.product_id = p.id
WHERE t.country = 'JP'
AND t.start_time >= '2026-09-01'
AND t.start_time < '2026-10-01'
GROUP BY p.id
) AS per_product;Show answer
19, not 20: prd_06 is gone. WHERE t.country = 'JP' drops the rows without a match (their t.country is NULL), and the LEFT JOIN turns into an inner join. Conditions on the right table go in ON.
This is what PostgreSQL returns for the query as it is:
| products_in_result |
|---|
| 19 |
Show the fix
SELECT COUNT(*) AS products_in_resultFROM ( SELECT p.id, COUNT(t.product_id) AS sales FROM products p LEFT JOIN transactions t ON t.product_id = p.id AND t.country = 'JP' AND t.start_time >= '2026-09-01' AND t.start_time < '2026-10-01' GROUP BY p.id) AS per_product;| products_in_result |
|---|
| 20 |
Conditions on the left table are different. They choose which X are in the report, so they go in WHERE. For merchants enrolled in the advances program only:
SELECT m.id, COUNT(cp.payout_id) AS payouts, COALESCE(SUM(cp.amount_usd), 0) AS paid_usdFROM merchants mLEFT JOIN channel_payouts cp ON cp.merchant_id = m.id AND cp.period_month = DATE '2026-08-01'WHERE m.advances_enrolled_at IS NOT NULLGROUP BY m.idORDER BY m.id;| id | payouts | paid_usd |
|---|---|---|
| mer_01 | 0 | 0 |
| mer_03 | 1 | 89.20 |
| mer_04 | 1 | 310.12 |
| mer_07 | 1 | 13.58 |
| mer_09 | 1 | 178.40 |
| mer_11 | 0 | 0 |
Another way to keep the right side clean is to filter it first in a CTE and then join the result. See Subqueries and CTE.
Count a column, not the row
Section titled “Count a column, not the row”After a LEFT JOIN, a merchant without payouts still has one row. COUNT(*) counts that row and returns 1. COUNT(cp.payout_id) counts only real matches, because the column is NULL in the row of NULLs. Count the right table’s key, or any column that is never NULL in a real row.
prd_06 has no sales in Japan in September. What do the two counters show?
Guess the result first, then run the query.
Tables, columns and how they connect
products — products (20 rows); a merchant can own several
id— key: prd_01 …
| id |
|---|
| prd_01 |
| prd_02 |
| prd_03 |
transactions — one row = one paid (or trial) period of a subscription
product_id— → products.idstart_time— start of the period = time of purchase; "started in …" means this columncountry— customer's country
| product_id | start_time | country |
|---|---|---|
| prd_01 | 2025-01-05 05:52:57 | IN |
| prd_01 | 2025-01-03 05:03:11 | BR |
| prd_01 | 2025-01-10 11:02:39 | JP |
Joins: transactions.product_id = products.id
"Today" is 2026-09-30 00:00 UTC. All times are UTC. Every run is rolled back, so you cannot break the data.
SELECT p.id,
COUNT(*) AS count_star,
COUNT(t.product_id) AS count_col
FROM products p
LEFT JOIN transactions t
ON t.product_id = p.id
AND t.country = 'JP'
AND t.start_time >= '2026-09-01'
AND t.start_time < '2026-10-01'
WHERE p.id = 'prd_06'
GROUP BY p.id;Show answer
count_star = 1, count_col = 0. After the LEFT JOIN, a product without a match keeps one row with NULL on the right, and COUNT(*) counts it. Count a column of the right table: COUNT(t.product_id).
This is what PostgreSQL returns for the query as it is:
| id | count_star | count_col |
|---|---|---|
| prd_06 | 1 | 0 |
COALESCE for sums
Section titled “COALESCE for sums”SUM over the row of NULLs is NULL. For a report, and always for money, turn it into 0: COALESCE(SUM(cp.amount_usd), 0). COUNT needs no COALESCE, because it already returns 0.
Be careful with columns of the left table. A left row without a match still carries its own values, so SUM of a left-table column returns that value, not 0. The second drill below has exactly this trap.
Two fact tables: aggregate each one first
Section titled “Two fact tables: aggregate each one first”“Every merchant with payouts and advances” needs two “many” tables. Two plain LEFT JOINs multiply each other’s rows. Aggregate each table to one row per merchant, then join both results to merchants:
WITH paid AS ( SELECT merchant_id, SUM(amount_usd) AS paid_usd FROM channel_payouts WHERE period_month = DATE '2026-08-01' GROUP BY merchant_id),advanced AS ( SELECT merchant_id, SUM(amount_usd) AS advanced_usd FROM advances WHERE period_month = DATE '2026-08-01' GROUP BY merchant_id)SELECT m.id, COALESCE(pd.paid_usd, 0) AS paid_usd, COALESCE(v.advanced_usd, 0) AS advanced_usdFROM merchants mLEFT JOIN paid pd ON pd.merchant_id = m.idLEFT JOIN advanced v ON v.merchant_id = m.idORDER BY m.id;The first four of 12 rows:
| id | paid_usd | advanced_usd |
|---|---|---|
| mer_01 | 0 | 125.45 |
| mer_02 | 154.57 | 0 |
| mer_03 | 89.20 | 175.44 |
| mer_04 | 310.12 | 384.11 |
mer_01 already received advances against August sales, and no marketplace has paid it yet. With two plain LEFT JOINs to the raw tables instead, mer_04’s payouts double from 310.12 to 620.24: its one payout row meets both of its advances. Row multiplication covers this in detail.
Practice
Section titled “Practice”Every product with the number of its refunded transactions that started in September 2026 — include products with zero. Test purchases excluded. Most refunds first, then product id.
Output columns: product_id, refundsOrder: ORDER BY refunds DESC, product_id
Tables, columns and how they connect
products — products (20 rows); a merchant can own several
id— key: prd_01 …
| id |
|---|
| prd_01 |
| prd_02 |
| prd_03 |
transactions — one row = one paid (or trial) period of a subscription
transaction_id— unique id of the transactionproduct_id— → products.idstart_time— start of the period = time of purchase; "started in …" means this columnrefunded_at— when the money was returned; NULL = no refund; "refunded" = refunded_at IS NOT NULLis_test— test purchase: exclude it from business numbers
| transaction_id | product_id | start_time | refunded_at | is_test |
|---|---|---|---|---|
| t_000001 | prd_03 | 2025-10-12 16:30:29 | NULL | false |
| t_000002 | prd_08 | 2025-06-25 19:26:50 | NULL | false |
| t_000144 | prd_12 | 2025-09-13 17:45:04 | 2025-09-20 20:52:05 | false |
Joins: transactions.product_id = products.id
"Today" is 2026-09-30 00:00 UTC. All times are UTC. Every run is rolled back, so you cannot break the data.
-- your query here
Show answer
Reference
SELECT p.id AS product_id, COUNT(t.transaction_id) AS refundsFROM products pLEFT JOIN transactions t ON t.product_id = p.id AND NOT t.is_test AND t.refunded_at IS NOT NULL AND t.start_time >= TIMESTAMP '2026-09-01' AND t.start_time < TIMESTAMP '2026-10-01'GROUP BY p.idORDER BY refunds DESC, p.id;Expected output
| product_id | refunds |
|---|---|
| prd_08 | 2 |
| prd_09 | 1 |
| prd_10 | 1 |
| prd_12 | 1 |
| prd_14 | 1 |
| prd_15 | 1 |
| prd_17 | 1 |
| prd_20 | 1 |
| prd_01 | 0 |
| prd_02 | 0 |
| prd_03 | 0 |
| prd_04 | 0 |
| prd_05 | 0 |
| prd_06 | 0 |
| prd_07 | 0 |
| prd_11 | 0 |
| prd_13 | 0 |
| prd_16 | 0 |
| prd_18 | 0 |
| prd_19 | 0 |
“Including zero” means: start from products and LEFT JOIN the transactions. Every condition on transactions goes in ON; in WHERE it would drop the products without a match. Count COUNT(t.transaction_id): COUNT(*) would give 1 instead of 0.
Stock on hand at the end of September 2026 for every item: id, name, units and value_usd (units × unit cost). Count only moves before 2026-10-01. An item with no moves before that date shows 0 units and 0 value. Item names are not unique. Order by item id.
Output columns: id, name, units, value_usdOrder: ORDER BY id
-- sample tables (each run rolls back: keep this block on top)
CREATE TEMP TABLE items (id int PRIMARY KEY, name varchar, unit_cost_usd numeric(10, 2));
CREATE TEMP TABLE stock_moves (id int PRIMARY KEY, item_id int REFERENCES items(id), moved_at date, qty int);
INSERT INTO items VALUES (1, 'Notebook', 3.50), (2, 'Pen', 1.20), (3, 'Pen', 0.80), (4, 'Stapler', 7.00), (5, 'Tape', 2.40);
INSERT INTO stock_moves VALUES (1, 1, '2026-09-01', 40), (2, 1, '2026-09-10', -15), (3, 2, '2026-09-03', 100),
(4, 2, '2026-09-20', -100), (5, 3, '2026-09-05', 25), (6, 1, '2026-10-02', -5),
(7, 5, '2026-10-03', 12);
-- RESULT: one row per …
-- AGREED: …
-- PLAN: …
Show answer
Reference
-- sample tables (each run rolls back: keep this block on top)CREATE TEMP TABLE items (id int PRIMARY KEY, name varchar, unit_cost_usd numeric(10, 2));CREATE TEMP TABLE stock_moves (id int PRIMARY KEY, item_id int REFERENCES items(id), moved_at date, qty int);INSERT INTO items VALUES (1, 'Notebook', 3.50), (2, 'Pen', 1.20), (3, 'Pen', 0.80), (4, 'Stapler', 7.00), (5, 'Tape', 2.40);INSERT INTO stock_moves VALUES (1, 1, '2026-09-01', 40), (2, 1, '2026-09-10', -15), (3, 2, '2026-09-03', 100), (4, 2, '2026-09-20', -100), (5, 3, '2026-09-05', 25), (6, 1, '2026-10-02', -5), (7, 5, '2026-10-03', 12);
SELECT i.id, i.name, COALESCE(SUM(mv.qty), 0) AS units, COALESCE(SUM(mv.qty), 0) * i.unit_cost_usd AS value_usdFROM items iLEFT JOIN stock_moves mv ON mv.item_id = i.id AND mv.moved_at < DATE '2026-10-01'GROUP BY i.id, i.name, i.unit_cost_usdORDER BY i.id;Expected output
| id | name | units | value_usd |
|---|---|---|---|
| 1 | Notebook | 25 | 87.50 |
| 2 | Pen | 0 | 0.00 |
| 3 | Pen | 25 | 20.00 |
| 4 | Stapler | 0 | 0.00 |
| 5 | Tape | 0 | 0.00 |
The items set the rows: FROM items i LEFT JOIN stock_moves mv. The date limit is a condition on the right table, so it goes in ON. In WHERE it would drop the Stapler, which has no moves at all, and the Tape, whose only move is on 3 October. WHERE mv.moved_at < … OR mv.moved_at IS NULL brings the Stapler back but still drops the Tape. COALESCE(SUM(mv.qty), 0) turns the NULL into 0 units, and the value is units × i.unit_cost_usd. Group by i.id: two items are called Pen, and grouping by name would merge them into one row. The trap: SUM(mv.qty) * i.unit_cost_usd without COALESCE gives NULL, not 0, for the Stapler and the Tape. The sum over no rows is NULL, and NULL times a price is still NULL.
Further reading
Section titled “Further reading”- Joined tables —
LEFT OUTER JOIN, with an example of a condition inONagainst the same condition inWHERE. - Joins between tables — the tutorial, including outer joins.
- COALESCE — the first value that is not NULL.
- Aggregate functions — the note that
sumof no rows returns NULL, not zero.
Related topics
Section titled “Related topics”- Joins — keys, and what a join does to the row count.
- NULL logic — why the row of NULLs fails every condition in
WHERE. - Row multiplication — two “many” tables in one query.
- Calendars and active periods — every day, even with no data:
generate_seriesandLEFT JOIN. - UNION ALL and reconciliation —
FULL OUTER JOINwhen either side can be missing.
Site content: CC BY 4.0. Code: MIT. The exercises run in your browser: PostgreSQL by PGlite, Python by Pyodide.