Orphans, mismatches and reconciliation
The hardest problems hide between tables, where each table looks fine on its own.
Orphans: rows pointing at something that doesn't exist.
SELECT COUNT(*)
FROM payments p
WHERE NOT EXISTS (SELECT 1 FROM invoices i WHERE i.id = p.invoice_id)A foreign key would have stopped these (Tier 4, module 2), but Brightwell's tables don't have one.
Mismatches: two tables that should agree, but don't. Each invoice belongs to an order, and both record the customer:
SELECT COUNT(*)
FROM invoices i
JOIN orders o ON o.id = i.order_id
WHERE i.customer_id <> o.customer_idReconciliation: totals that should match, worked out two ways. An invoice's net_amount should
equal its order's lines plus shipping. Work out the order totals in a CTE, join them to the
invoices, and count the differences bigger than a penny (ABS(a - b) > 0.01).
Reconciliation is how finance teams catch problems: if the invoices and the order lines disagree, one of them is wrong, and someone has to find out which.