FULL OUTER JOIN Reconciliation Diff

Join ledgers from both sides, keep only rows with NULL on either side or mismatched amounts, and label each difference with a CASE.

SqlData Integrity

Code

snippet
-- 两份台账 reconciliation diff:FULL OUTER JOIN 保留两侧都未被匹配的行
-- 左侧为 NULL = 只在 b 里;右侧为 NULL = 只在 a 里
SELECT
    COALESCE(a.account_id, b.account_id)     AS account_id,
    CASE
        WHEN a.account_id IS NULL THEN 'only_in_b'
        WHEN b.account_id IS NULL THEN 'only_in_a'
        ELSE 'amount_mismatch'
    END                                      AS difference,
    a.amount_cents                           AS a_amount,
    b.amount_cents                           AS b_amount
FROM ledger_a a
FULL OUTER JOIN ledger_b b
    ON b.account_id = a.account_id
WHERE a.account_id IS NULL
   OR b.account_id IS NULL
   OR a.amount_cents <> b.amount_cents;

How the snippet works

What runs is SELECT, with ledger_a and ledger_b as the object involved.

Breaking the statements into their working parts: one JOIN combining rows across tables; a WHERE clause that keeps only the rows a statement is meant to touch.

Applying it

Point it at the ledger_a table.

Interactive Tools for This Topic

FAQ

Which objects does the SQL touch?
`ledger_a`, `ledger_b`, combined through a join.