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.
Code
-- 两份台账 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
SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.Date Difference CalculatorCalculate the number of days, weeks, whole months, and years between two ISO dates, computed in UTC.Diff Ignoring WhitespaceCompare two blocks of text line by line and separate true differences from lines that differ only in spacing, indentation, or line endings.
FAQ
- Which objects does the SQL touch?
- `ledger_a`, `ledger_b`, combined through a join.
Report a problem with this exampleOpens a pre-filled issue on GitHub.