RIGHT and FULL JOIN: reconcile two data sources
Overview
RIGHT JOIN preserves the right input, while FULL OUTER JOIN preserves unmatched rows from both inputs along with all matching pairs. Two independent lists such as expected and observed inventory scans can contain records missing from either side. The supplemental fixture models that case without breaking shop foreign keys.
First example
SELECT e.id, o.idFROM join_expected AS e RIGHT JOIN join_observed AS o ON e.code = o.codeORDER BY o.id, e.id;Observed SQLite result (rows in JSON):
[ [ 1, 10 ], [ 1, 11 ], [ null, 12 ], [ null, 13 ]]How it works
join_expected contains (id, code) pairs (1,A), (2,B), (3,NULL); join_observed contains (10,A), (11,A), (12,C), (13,NULL). A matches twice, B and C occur on only one side, and NULL = NULL is UNKNOWN, not a match. Thus RIGHT JOIN yields four rows and FULL yields six. Inspect non-NULL source ids to distinguish missing sides; nullable codes are not reliable existence markers. A RIGHT JOIN can be rewritten as a LEFT JOIN by swapping inputs and retaining explicit projection. PostgreSQL 17 supports both; SQLite added RIGHT and FULL in 3.39.0, and these tests run on the installed version. For older engines verify support before choosing syntax; UNION ALL with a LEFT JOIN branch and a right-only unmatched branch can emulate FULL when the missing-side test uses a guaranteed non-NULL id.
Practical example
SELECT e.id, o.idFROM join_expected AS e FULL OUTER JOIN join_observed AS o ON e.code = o.codeORDER BY e.id NULLS LAST, o.id NULLS LAST;Observed SQLite result (rows in JSON):
[ [ 1, 10 ], [ 1, 11 ], [ 2, null ], [ 3, null ], [ null, 12 ], [ null, 13 ]]Practice and mistakes
Practice: use a FULL JOIN and select only rows whose expected id or observed id is NULL. Predict four unmatched rows, including the two NULL-code records. Do not use UNION (without ALL) as a universal emulation because it can remove legitimate duplicate result rows.