Skip to content

Reconcile invoices and receipts in SQL

Build one row per invoice, keep unpaid bills visible, and put receipts with a missing invoice into a separate check.

25 minAnalysts, operators and builders who work with reports

Start the guide

Open the practice close

Use any SQLite editor. Open the supplied database. In DB Browser for SQLite, choose Open Database, then Execute SQL. The two CSVs contain the same data for anyone who wants to inspect it in a spreadsheet.

Start with independent control totals.
SourceRowsDollar total
Invoices5$500 billed
Receipts7$435 received

Run the join that breaks the total

Open starter.sql and run its SELECT. Seven rows appear. I104 has an empty receipt because it has no payment. Locate both rows for I101 and both for I103. Compare the $820 billed sum in this join with the $500 invoice source.

Reduce payments to one row per invoice

Use the first part of the worked invoice query to sum paid_usd and group by invoice_id. Join that small result to invoices using a LEFT JOIN. Replace a missing payment total with zero using COALESCE. Subtract the matched amount from the billed amount for each open balance.

See a worked example

I103 is billed $200 and has payments of $100 and $80. Its report line is $200 billed, $180 matched and $20 open.

Account for the missing $15

Run the unmatched-receipt query in solution.sql. It starts from receipts and keeps rows where the invoice lookup fails. R07 references I999. Add the $15 from that list to the $420 matched payments to explain all $435 received.

Run the second close

Save a fresh copy of the practice database. Execute second-close.sql once on that copy, then rerun the solution. It adds an $80 invoice paid in two installments and a $25 receipt on I104.

Check your result

The first run returns five invoices, $500 billed, $420 matched and $80 open, with R07 for $15 outside the report. The second run returns six invoices, $580 billed, $525 matched and $55 open. R07 still needs review.

If your result looks different

If I104 disappears on the first run, check the direction of the join and any WHERE clause on receipts. If two $80 invoices collapse in the second run, remove DISTINCT from the amount and group using invoice IDs. If second-close.sql says an ID already exists, reopen a fresh practice copy.