30 RIGHT and FULL JOIN
RIGHT JOIN mirrors LEFT JOIN: every row from the right side is kept, even if the left side has no match. FULL OUTER JOIN keeps everything from both sides, filling unmatched columns with NULL. In practice, LEFT JOIN is far more common than RIGHT JOIN — it usually reads more naturally to put the “primary” table first and use LEFT JOIN to bring in supplemental data. FULL JOIN shines when you need to see matches and both kinds of orphans at once (e.g. reconciliation reports).
What you’ll learn
RIGHT JOIN: keep everything on the rightFULL JOIN: keep everything on both sides- Why
LEFT JOINusually wins on readability - Detecting unmatched rows:
WHERE other.id IS NULL - Ordering when both sides may be NULL
Example
RIGHT JOIN A ON ... is exactly LEFT JOIN A with the tables swapped — A LEFT JOIN B ON cond is the same as B RIGHT JOIN A ON cond. Most style guides recommend rewriting RIGHT JOIN to LEFT JOIN so the “primary” table appears first in the FROM clause.
FULL OUTER JOIN is the symmetric counterpart: every row from both sides appears, and unmatched columns are NULL. Order 3 (customer_id = 99) appears with NULL name; Bob and Carol appear with NULL order columns. The ORDER BY ... NULLS LAST keeps the result readable.
The classic anti-join pattern — “rows in A that have no match in B” — uses LEFT JOIN ... WHERE B.id IS NULL. PostgreSQL recognizes this idiom and often plans it as an efficient anti-join.
Run the example
To run (requires the tables from the previous lesson):
Common pitfalls
- Writing
RIGHT JOINand then needing to flip the columns mentally. Swap the table order and useLEFT JOINfor readability. FULL JOINresults have NULLs on both sides; anORDER BYwithoutNULLS LAST/FIRSTcan scatter them confusingly.WHERE other.id IS NULLafter aLEFT JOINis the anti-join idiom.NOT EXISTS (...)andNOT IN (...)are alternatives —NOT EXISTSis usually the safest with NULLs.- Joining multiple tables with
FULL JOINis rarely what you want — the cartesian-like behavior compounds. Stick to simple cases.
For “show me the symmetric difference of two sets” (rows in one but not the other), FULL OUTER JOIN ... WHERE a.id IS NULL OR b.id IS NULL is the idiom — handy for reconciling two snapshots of the same data.
Add a WHERE clause to the FULL JOIN to show only the unmatched rows: WHERE c.id IS NULL OR o.id IS NULL. Then rewrite the RIGHT JOIN above as a LEFT JOIN by swapping the table order — convince yourself the result is the same.
Downloads
SQL file: right-and-full-join.sql · All lesson files · Setup guide