Skip to content

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.

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_usd
FROM merchants m
LEFT JOIN channel_payouts cp
ON cp.merchant_id = m.id
AND cp.period_month = DATE '2026-08-01'
GROUP BY m.id
ORDER BY m.id;

The first three of 12 rows:

idpayoutspaid_usd
mer_0100
mer_021154.57
mer_03189.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_usd
FROM merchants m
LEFT 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;
idpayout_idchannelamount_usd
mer_01NULLNULLNULL
mer_02po_0026south_market154.57

mer_01 has no payout for August, so it gets one row of NULLs. The next three rules all come from this row.

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.

SQLTrap: what will it return?core

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.id
  • start_time — start of the period = time of purchase; "started in …" means this column
  • country — customer's country
product_idstart_timecountry
prd_012025-01-05 05:52:57IN
prd_012025-01-03 05:03:11BR
prd_012025-01-10 11:02:39JP

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_result
FROM (
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
1 row

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_usd
FROM merchants m
LEFT 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 NULL
GROUP BY m.id
ORDER BY m.id;
idpayoutspaid_usd
mer_0100
mer_03189.20
mer_041310.12
mer_07113.58
mer_091178.40
mer_1100

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.

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.

SQLTrap: what will it return?core

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.id
  • start_time — start of the period = time of purchase; "started in …" means this column
  • country — customer's country
product_idstart_timecountry
prd_012025-01-05 05:52:57IN
prd_012025-01-03 05:03:11BR
prd_012025-01-10 11:02:39JP

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:

idcount_starcount_col
prd_0610

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.

“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_usd
FROM merchants m
LEFT JOIN paid pd ON pd.merchant_id = m.id
LEFT JOIN advanced v ON v.merchant_id = m.id
ORDER BY m.id;

The first four of 12 rows:

idpaid_usdadvanced_usd
mer_010125.45
mer_02154.570
mer_0389.20175.44
mer_04310.12384.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.

SQLWrite a querycore

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 transaction
  • product_id — → products.id
  • start_time — start of the period = time of purchase; "started in …" means this column
  • refunded_at — when the money was returned; NULL = no refund; "refunded" = refunded_at IS NOT NULL
  • is_test — test purchase: exclude it from business numbers
transaction_idproduct_idstart_timerefunded_atis_test
t_000001prd_032025-10-12 16:30:29NULLfalse
t_000002prd_082025-06-25 19:26:50NULLfalse
t_000144prd_122025-09-13 17:45:042025-09-20 20:52:05false

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 refunds
FROM products p
LEFT 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.id
ORDER BY refunds DESC, p.id;

Expected output

product_idrefunds
prd_082
prd_091
prd_101
prd_121
prd_141
prd_151
prd_171
prd_201
prd_010
prd_020
prd_030
prd_040
prd_050
prd_060
prd_070
prd_110
prd_130
prd_160
prd_180
prd_190
20 rows

“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.

SQLWrite a query

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_usd
FROM items i
LEFT 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_usd
ORDER BY i.id;

Expected output

idnameunitsvalue_usd
1Notebook2587.50
2Pen00.00
3Pen2520.00
4Stapler00.00
5Tape00.00
5 rows

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.

Site content: CC BY 4.0. Code: MIT. The exercises run in your browser: PostgreSQL by PGlite, Python by Pyodide.