runtime
24 / 88

lesson 24 Joins & sets · intermediate

FULL OUTER JOIN & unmatched records

Compare both sides of a relationship, including unmatched rows.

the idea

FULL OUTER JOIN keeps unmatched rows from both sides. Reconciliation often needs this to find missing records. This SQLite version supports FULL OUTER JOIN; older SQLite versions did not.

tables in this lesson

The challenges use this data. Each column shows its type underneath; → marks a link to another table.

invoices4 columns · 6 rows
idinteger · keyaccount_idintegerperiodtextbilled_amountreal
112025-0120
232025-0180
342025-0120
462025-0180
512025-0220

showing 5 of 6 rows

payments3 columns · 7 rows
idinteger · keyinvoice_idintegeramountreal
1110
2110
3280
4315
5480

showing 5 of 7 rows

example

The idea in one query. Press Run to see what it returns; running examples never affects your progress.

example.sql
SELECT i.id AS invoice_id,p.id AS payment_id
FROM invoices i
FULL OUTER JOIN payments p ON p.invoice_id=i.id;

Watch for: Split payments make one invoice match more than one payment.

build it step by step

Each step changes one thing. Run them in order and watch the result change.

  1. See invoice and payment keys. Some invoices lack payments and some payments lack invoices. FULL OUTER JOIN keeps unmatched rows from both sides.

    step-1.sql
    SELECT i.id AS invoice_id, p.id AS payment_id
    FROM invoices i
    LEFT JOIN payments p ON p.invoice_id = i.id
    ORDER BY i.id, p.id;
  2. Retain unmatched rows on both sides. FULL OUTER JOIN returns matches plus leftovers from either table. Missing matches show NULL on the empty side.

    step-2.sql
    SELECT i.id AS invoice_id, p.id AS payment_id
    FROM invoices i
    FULL OUTER JOIN payments p ON p.invoice_id = i.id;

challenge 1

Return invoice_id and payment_id for every invoice/payment match, retaining unmatched rows on either side. Keep split payments as separate rows.

Return invoice_idpayment_idany row order

challenge-1.sql
 
To master this lesson, solve both challenges without hints and pass the concept check. 3 of 3 to go.