A Left Join Keeps Unmatched Left Rows

A left join returns matching pairs plus a null-extended result for a left row with no right match.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Trace an inactive category
  2. Preserve what the nulls mean
  3. Preserve a parent row where no match exists
  4. Distinguish absence of a child from a nullable child attribute

Trace an inactive category

With a left table of two categories and only one with articles, the category without articles can still appear. Its article fields are null. Inner joins would only yield matched pairs.

Preserve what the nulls mean

A missing child ID can distinguish no match if matched children always have an ID. A nullable child description can instead be absent even on a match. Null meanings guide the field choice.[1]

Preserve a parent row where no match exists

Two branches have IDs one and two. Only branch one has an office record. A left join from branches keeps both, with office fields null on the unmatched row. This affects filters and counting. See counting related records.

WITH branches(id) AS (VALUES (1), (2)), offices(branch_id, code) AS (VALUES (1,'A'))
SELECT b.id, o.code FROM branches b LEFT JOIN offices o ON o.branch_id = b.id ORDER BY b.id;
-- Expected: (1,A), (2,null).

Distinguish absence of a child from a nullable child attribute

A matching office could itself have null code under another schema. Inspect a non-null child identity to detect whether a real match exists. Test both kinds of null.

References

  1. PostgreSQL Global Development Group, Queries ↩