Find conflicting facts across tables
Join on the shared key and filter with <> on the facts that must match: every hit is one table contradicting the other.
The task
orders.total and invoices.amount should tell the same story for the same order. Discounts applied in one system and not the other make them drift. This finds the drift.
The snippet
Runs unchanged on current versions of SQL Server, PostgreSQL, MySQL, SQLite and Oracle.
SELECT i.id AS invoice_id, i.order_id,
i.amount AS invoice_amount,
o.total AS order_total,
i.amount - o.total AS discrepancy
FROM invoices i
JOIN orders o ON o.id = i.order_id
WHERE i.amount <> o.total
ORDER BY ABS(i.amount - o.total) DESC;
仕組み
The join pairs each invoice with its order on the shared id; the WHERE keeps pairs whose money facts disagree. Computing the discrepancy per row (and ordering by its absolute size) turns the list into a reconciliation worklist, biggest mismatches first. Rows with no counterpart on either side need the orphan checks instead.
Variations
Include unpaired rows in the conflict report
SELECT i.id AS invoice_id, i.order_id,
i.amount AS invoice_amount, o.total AS order_total,
CASE WHEN o.id IS NULL THEN 'no matching order'
ELSE 'amounts differ' END AS issue
FROM invoices i
LEFT JOIN orders o ON o.id = i.order_id
WHERE o.id IS NULL OR i.amount <> o.total;
Tolerance-based comparison for floats
SELECT i.id, i.order_id, i.amount, o.total
FROM invoices i
JOIN orders o ON o.id = i.order_id
WHERE ABS(i.amount - o.total) > 0.005;
Questions that come up
Why the ABS tolerance variant for money?
Only when one side is a FLOAT or REAL column, or the amounts arrived through floating-point code. Binary floating point stores 0.1 approximately, so two logically equal amounts can differ by a hair and a strict <> flags them. Comparing the absolute difference against half a cent (0.005) absorbs that noise while still catching real discrepancies. With DECIMAL or NUMERIC on both sides the plain <> is exact and the tolerance only hides rounding differences you may want to see.
Keep reading
Related on SQLly
Run these with autocomplete that knows your tables
SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.