Postgres LEFT JOIN: keep zero rows and report grain
Carry one tenant report through ON versus WHERE, count non-null keys and a second one-to-many fan-out; prove one row per tenant using result invariants.
Quick answer
A Postgres LEFT JOIN preserves unmatched parent rows before later filters run. Put child eligibility in the join or child aggregate, count a non-null child key, and reduce independent child collections to the report grain before combining them. COALESCE replaces a missing measure; it cannot restore an eliminated parent.
On this page
When a Postgres LEFT JOIN report loses rows that should show zero, check the report's row grain and predicate placement before adding COALESCE. A filter on the right-hand table in WHERE can discard the row the outer join preserved. Put child eligibility in the join or a child aggregate, count a non-null child key, and verify that later joins do not multiply the count. [1][2][4]
What must one report row mean?#
Write the report's invariant in plain language first. For the case below, the result must contain exactly one row for every enabled tenant, with its paid-order count and active-seat count. A tenant with no qualifying activity must still appear. This statement determines which filters choose tenants and which filters choose children.
Scenario: a hypothetical SaaS report lists enabled tenants. Aster has paid and cancelled orders, Birch has only a cancelled order, Cedar has no orders, and disabled Dune must not appear. The names and data are invented fixtures. They are deliberately small enough that a reviewer can compute the intended result without trusting the query.
CREATE TEMP TABLE tenants (
id integer PRIMARY KEY,
name text NOT NULL,
enabled boolean NOT NULL
);
CREATE TEMP TABLE orders (
id integer PRIMARY KEY,
tenant_id integer NOT NULL REFERENCES tenants(id),
status text NOT NULL
);
CREATE TEMP TABLE seats (
id integer PRIMARY KEY,
tenant_id integer NOT NULL REFERENCES tenants(id),
active boolean NOT NULL
);
INSERT INTO tenants VALUES
(1, 'Aster', true), (2, 'Birch', true),
(3, 'Cedar', true), (4, 'Dune', false);
INSERT INTO orders VALUES
(11, 1, 'paid'), (12, 1, 'paid'),
(13, 1, 'cancelled'), (21, 2, 'cancelled'),
(41, 4, 'paid');
INSERT INTO seats VALUES
(101, 1, true), (102, 1, true), (103, 1, true),
(104, 1, false), (201, 2, true);Keep the base population separate from activity. tenants.enabled determines membership in this report, so it belongs in the base-row selection. An order's status determines whether that order contributes to a tenant's measure. Those are different decisions even though both use predicates.
Check the product requirement before changing the query. If a product owner actually wants only tenants with paid orders, an inner join or an existence condition can express that. Preserving every enabled tenant would then be wrong. Establish the desired population before treating every missing row as a SQL defect.
Why did the cancelled-only tenant disappear?#
The filter was evaluated after the outer join had already formed its rows. Consider this tempting query:
SELECT t.id, t.name, count(o.id) AS paid_orders
FROM tenants AS t
LEFT JOIN orders AS o ON o.tenant_id = t.id
WHERE t.enabled AND o.status = 'paid'
GROUP BY t.id, t.name
ORDER BY t.id;The join finds Birch's cancelled order, so Birch has a real joined row. The status predicate rejects that row. Cedar's unmatched row has null right-side columns, and its status comparison does not evaluate to true either. Both tenants disappear from the final result. PostgreSQL documents the logical difference between an outer-join condition and a later WHERE restriction. [1]
Adding OR o.id IS NULL is an incomplete repair. It can preserve Cedar's null-extended row, but Birch already matched a cancelled order. No null-extended row was created for Birch, so there is nothing for that added condition to rescue. This is why a fixture containing only a paid tenant and an empty tenant gives false confidence.
For the stated report, child eligibility belongs in the join condition:
SELECT t.id, t.name, count(o.id) AS paid_orders
FROM tenants AS t
LEFT JOIN orders AS o
ON o.tenant_id = t.id AND o.status = 'paid'
WHERE t.enabled
GROUP BY t.id, t.name
ORDER BY t.id;Now Birch has no order satisfying the complete join condition, so the outer join supplies a null-extended row. Cedar receives the same treatment. The result can retain both tenants while the paid-order aggregate sees no non-null order key for either. That conclusion follows from the fixture and join semantics; it is not a claim about the production planner's physical execution order. [1][2]
Avoid the blanket rule that every right-table condition belongs in ON. A later predicate can intentionally select report rows. Ask whether the condition chooses a child to count or a tenant to display. Making that decision explicit keeps a correct outer join from being changed merely to satisfy a style preference.
Which aggregate actually counts orders?#
Use the identifier of a qualifying order. count(*) counts the null-extended joined row too, while count(o.id) ignores its null key. The latter produces the desired zero only if the counted expression is non-null for every real order being measured. Our fixture declares the order key as a primary key. [2]
Counting another nullable column can silently undercount real children. For example, a future optional external reference would be a poor proxy for order existence. If the report measures orders, count an order identifier. If it measures orders that have an external reference, state that narrower measure in the column name and specification.
COALESCE cannot restore a tenant that WHERE already removed. It chooses a replacement value for a null expression in a row that survives. PostgreSQL's conditional-expression documentation defines that behavior. Use it to normalize a missing pre-aggregated measure, not as a substitute for preserving the base population. [4]
An aggregate FILTER is another useful tool when the joined input must support multiple measures. PostgreSQL allows each aggregate to choose which input rows contribute, and aggregate expressions belong in the query's result list or HAVING context rather than serving as ordinary base-row predicates. [3]
SELECT t.id, t.name,
count(o.id) AS all_orders,
count(o.id) FILTER (WHERE o.status = 'paid') AS paid_orders
FROM tenants AS t
LEFT JOIN orders AS o ON o.tenant_id = t.id
WHERE t.enabled
GROUP BY t.id, t.name
ORDER BY t.id;This query retains cancelled orders in the joined input because the report also needs the all-order count. It then filters the paid measure alone. Choose this shape because it expresses the measures clearly. Do not assume it is automatically faster or slower than pre-filtering; that depends on the actual query, data and plan.
What changes when another child table joins?#
Independent one-to-many joins can multiply the input rows before aggregation. If the report joins Aster's paid orders directly to its active seats, every matching order can pair with every matching seat. Counting order identifiers in that expanded input counts pairs, not distinct orders.
For the illustrative fixture, Aster has two paid orders and three active seats. A direct join produces six qualifying pairs. Both counts would be inflated if the query simply applied count(o.id) and count(s.id) to those pairs. This is fixture arithmetic, not a database benchmark.
COUNT(DISTINCT o.id) can recover the order count in that particular join. It does not establish that other measures remain correct. A sum of order amounts would still be vulnerable to repeated rows, and SUM(DISTINCT amount) would wrongly collapse separate orders with equal amounts. Review every measure rather than treating DISTINCT as a general cure.
An explicit alternative is to reduce each child relation to the desired parent grain before joining it to the tenant list:
WITH paid AS (
SELECT tenant_id, count(*) AS paid_orders
FROM orders
WHERE status = 'paid'
GROUP BY tenant_id
), active AS (
SELECT tenant_id, count(*) AS active_seats
FROM seats
WHERE active
GROUP BY tenant_id
)
SELECT t.id, t.name,
coalesce(p.paid_orders, 0) AS paid_orders,
coalesce(a.active_seats, 0) AS active_seats
FROM tenants AS t
LEFT JOIN paid AS p ON p.tenant_id = t.id
LEFT JOIN active AS a ON a.tenant_id = t.id
WHERE t.enabled
ORDER BY t.id;Each child aggregate contributes at most one row per tenant. A missing aggregate row becomes a null measure after the join, which is precisely where COALESCE belongs. The query's structure now makes the report grain visible to a reviewer. It does not promise a particular CTE materialization strategy or plan. [1][2][4]
| Tenant fixture | Paid orders expected | Active seats expected | Purpose |
|---|---|---|---|
| Aster | 2 | 3 | Exposes multiplication between independent children |
| Birch | 0 | 1 | Exposes the cancelled-only rescue failure |
| Cedar | 0 | 0 | Checks null extension and zero presentation |
| Dune | Absent | Absent | Checks the base-population filter |
The table is an expected result derived from invented inputs. Treat both missing and extra rows as failures. Matching the totals while duplicating a tenant row is insufficient when downstream code expects one record per tenant.
How do you prove the rewrite before tuning it?#
First compare the complete result against the fixture's expected rows. Then test transformations that should preserve the report's meaning. Adding a cancelled order must not increase the paid count. Adding an inactive seat must not change the active-seat count. Adding another active seat must not change the paid-order count.
Adding a seat must not change an order count, even when the overall report total still looks plausible. Keep that assertion when adding another child relation. If someone adds another one-to-many table, the invariant that an unrelated child cannot alter existing counts should fail before the report is shipped.
Include a tenant with no children and a tenant with children that all fail eligibility. They exercise different paths. Include repeated amounts if monetary measures are added. Include any soft-delete or reporting-window conditions in the fixture as explicit inputs, with expected membership agreed by the report owner.
Reporting windows deserve their own boundary fixtures. If the product definition says a paid order belongs to the period containing its payment timestamp, filtering on order creation time answers a different question even when the join is correct. Put records immediately before, at and after the chosen boundary into the fixture. Keep the expected membership beside those inputs so a later rewrite cannot change the period silently.
Decide what an absent measure means too. The fixture treats an absent paid aggregate as a known zero because all eligible orders are available to the query. If an upstream import has not completed, the product might instead need an explicit incomplete state. Substituting zero for missing data would then hide an operational failure. SQL can express the agreed presentation, but the report owner must distinguish no activity from unavailable evidence.
Finally, verify the result as the application reads it. A database result with one row per tenant can still be reshaped incorrectly by a mapper keyed on a non-unique display name. Use stable identifiers when comparing expected rows and carry those identifiers into downstream assertions. A query review is finished when the consumer receives the agreed population and measures, not when a screenshot of a total looks reasonable.
Only after those results are correct should you inspect the production-shaped plan. PostgreSQL's EXPLAIN shows the planner's chosen query structure and estimates. EXPLAIN ANALYZE actually executes the statement, so use an appropriate environment and understand the statement's effects before running it. An attractive plan cannot prove that the query answers the intended question. [6]
Potential indexes and aggregation strategies depend on tenant selectivity, eligibility predicates, table size and data distribution. Record the plan and representative workload rather than promising that a particular index will repair every report. A small enabled-tenant subset may justify a different access pattern from a full-population export. [6]
When should you use a different shape?#
Use EXISTS when the report needs presence rather than a count or child attributes. It asks whether a qualifying row exists and avoids making the child relation part of the report's row grain. PostgreSQL documents existence tests separately from membership tests; choose the operator that matches the question. [5]
For example, a list of enabled tenants with any paid order can use a correlated existence condition. A list that must also include tenants with no paid orders needs a different presentation of that condition. Neither requirement is served by blindly moving the same predicate between clauses.
For an anti-join question, such as tenants without a qualifying order, our Postgres missing-row guide covers the separate null and membership decision. This article's question is aggregation over a preserved population, so its acceptance criteria include measure values as well as membership.
The SQL targets PostgreSQL 18 and follows its documented join and aggregate semantics. The fixture is illustrative. No production database, representative query plan or performance measurement is claimed here. A local relational fixture can check the expected rows, but deployment readiness still requires verification on the target database, schema, permissions and workload. [1][6]
Questions about missing report rows#
- Why does OR child.id IS NULL fail for some parents?
- A parent with an ineligible child already has a joined row, so the join does not also create a null-extended fallback. A later status filter can remove that real row. Filter eligible children before null extension when the parent must remain. [1]
- Should I wrap every count in COALESCE?
- No. A direct
countaggregate returns a count, including zero for no contributing non-null keys.COALESCEis useful when a separately aggregated child row is absent after an outer join. It cannot restore an eliminated parent. [2][4] - Is COUNT DISTINCT always the safest repair?
- It can make a specific identifier count correct after fan-out, but it does not repair every other measure in the query. Check sums, averages and row membership separately. Reducing each child relation to the intended grain often makes the contract clearer.
- Can EXPLAIN prove the report is correct?
- It reveals the plan, not the business meaning. Prove the expected population and measures with adversarial fixtures first. Then use representative plans to investigate cost and row estimates; execution-based analysis runs the statement. [6]