Capstone: Fee Tracker Payment Reconciliation
Reconciliation means proving that two records of the same money agree: here, the payments the Fee Tracker recorded and the deposits the bank actually received. Finance teams do this every month. A payment with no matching deposit might never have arrived; a deposit with no matching payment is money nobody recorded; a fee the bank took needs an entry of its own. In this capstone, you build the whole monthly reconciliation for the tutoring program in nine milestones, each a separate sitting with a clear deliverable and an automated check that says PASS or FAIL. Together they use almost everything in the course, and each milestone names the lessons to review if you get stuck. Work through them in order; attempt each one before opening its solution.
In One Minute
- Inputs: the Fee Tracker's 7
payments, and the bank statement from Project: Data Cleanup. - Goal: a
matchestable pairing each payment with one statement line, and a list of exceptions. - Matching rule: same amount and same date is exact; same amount within 3 days is near.
- Expected result: 4 exact matches, 3 near matches, every payment matched, and 2 exceptions: a $12.00 bank fee and a $1,450.00 deposit nobody recorded.
- Data in Try it: milestones 1 and 2 use the bank-statement dataset; milestones 3 to 9 use reconciliation, which holds the result of milestones 1 and 2.
| # | Milestone | Deliverable | Review |
|---|---|---|---|
| 1 | Design the database | Tables and constraints for statement lines and matches | Data Modeling, Constraints |
| 2 | Import and validate | Clean statement lines; rejects counted | Project: Data Cleanup |
| 3 | Write matching queries | Exact, then near matches | Joins, EXISTS, SELECT DISTINCT |
| 4 | Identify exceptions | Unmatched payments and statement lines | LEFT JOIN, UNION and UNION ALL |
| 5 | Transactional posting | All-or-nothing matching | Transactions |
| 6 | Audit and permissions | A change log; a read-only accountant | Triggers, Users, Roles and Privileges |
| 7 | Optimize | Indexes for the matching join | Indexes, Reading EXPLAIN |
| 8 | Application and tests | A Python program with tests | SQL from Python, Testing SQL |
| 9 | Back up and restore | A verified copy | Backup and Restore |
Milestone 1: Design the Database
Deliverable: a migration that creates statement_lines and matches. A payment can match at most one statement line and each line at most one payment; every match records how it was made.
Show solution
CREATE TABLE statement_lines (
line_id INTEGER PRIMARY KEY,
account_id INTEGER NOT NULL REFERENCES bank_accounts (account_id),
posted_on DATE NOT NULL,
description VARCHAR(80) NOT NULL,
amount_usd NUMERIC(10,2) NOT NULL CHECK (amount_usd <> 0)
);
CREATE TABLE matches (
payment_id INTEGER PRIMARY KEY REFERENCES payments (payment_id),
line_id INTEGER NOT NULL UNIQUE REFERENCES statement_lines (line_id),
kind VARCHAR(10) NOT NULL CHECK (kind IN ('exact', 'near')),
matched_on DATE NOT NULL
);
-- Check: the required keys and constraints exist
SELECT CASE WHEN count(*) = 6 THEN 'PASS' ELSE 'FAIL' END AS milestone_1,
count(*) AS constraints_found
FROM information_schema.table_constraints
WHERE table_name IN ('statement_lines', 'matches')
AND constraint_type IN ('PRIMARY KEY', 'FOREIGN KEY', 'UNIQUE');CREATE TABLE
CREATE TABLE
milestone_1 | constraints_found
-------------+-------------------
PASS | 6
(1 row)Explanation: payment_id is the primary key of matches, so a payment can appear only once; line_id is UNIQUE, so a line can be used only once. Together they make the matching one-to-one without any application code. The check counts the six key constraints the design needs: in statement_lines, a primary key and a foreign key to the bank account; in matches, a primary key, two foreign keys and the unique line_id. If anyone later drops one, the check fails.
Milestone 2: Import and Validate the Statement
Deliverable: load the cleaned lines from statement_raw into statement_lines; reject unreadable lines; remove the duplicate. This repeats Project: Data Cleanup in compact form.
Show solution
CREATE TABLE statement_lines (
line_id INTEGER PRIMARY KEY, account_id INTEGER NOT NULL REFERENCES bank_accounts,
posted_on DATE NOT NULL, description VARCHAR(80) NOT NULL,
amount_usd NUMERIC(10,2) NOT NULL CHECK (amount_usd <> 0)
);
WITH cleaned AS (
SELECT line_no,
CASE
WHEN posted ~ '^\d{4}-\d{2}-\d{2}$' AND pg_input_is_valid(posted, 'date') THEN posted::date
WHEN posted ~ '^\d{1,2}/\d{1,2}/\d{4}$' THEN to_date(posted, 'MM/DD/YYYY')
END AS posted_on,
upper(regexp_replace(trim(description), '\s+', ' ', 'g')) AS description,
CASE
WHEN pg_input_is_valid(replace(replace(amount, '$', ''), ',', ''), 'numeric')
THEN round(replace(replace(amount, '$', ''), ',', '')::numeric, 2)
END AS amount_usd
FROM statement_raw
)
INSERT INTO statement_lines
SELECT DISTINCT ON (posted_on, description, amount_usd)
line_no, 1, posted_on, description, amount_usd
FROM cleaned
WHERE posted_on IS NOT NULL AND amount_usd IS NOT NULL
ORDER BY posted_on, description, amount_usd, line_no;
-- Check: 9 lines loaded, totaling the expected amount
SELECT CASE WHEN count(*) = 9 AND sum(amount_usd) = 3588.00 THEN 'PASS' ELSE 'FAIL' END AS milestone_2,
count(*) AS loaded, sum(amount_usd) AS total_usd
FROM statement_lines;CREATE TABLE
WITH
milestone_2 | loaded | total_usd
-------------+--------+-----------
PASS | 9 | 3588.00
(1 row)Explanation: Nine lines load, the same nine as in the cleanup project, and their total is checked to the cent, so a line that was dropped or doubled by mistake would fail the check even if the count happened to be right.
Milestone 3: Write the Matching Queries
Deliverable: fill matches, first with exact matches (same amount, same date), then with near matches (same amount, within 3 days) among what's left. From here on, the reconciliation dataset already contains the tables and lines from milestones 1 and 2.
Show solution
-- Exact: same amount, same day
INSERT INTO matches (payment_id, line_id, kind, matched_on)
SELECT p.payment_id, l.line_id, 'exact', DATE '2026-01-08'
FROM payments AS p
JOIN statement_lines AS l
ON l.amount_usd = p.amount_usd AND l.posted_on = p.paid_on
ON CONFLICT DO NOTHING;
-- Near: same amount within 3 days, closest line first, among unmatched rows
INSERT INTO matches (payment_id, line_id, kind, matched_on)
SELECT DISTINCT ON (p.payment_id) p.payment_id, l.line_id, 'near', DATE '2026-01-08'
FROM payments AS p
JOIN statement_lines AS l
ON l.amount_usd = p.amount_usd AND abs(l.posted_on - p.paid_on) <= 3
WHERE NOT EXISTS (SELECT 1 FROM matches m WHERE m.payment_id = p.payment_id)
AND NOT EXISTS (SELECT 1 FROM matches m WHERE m.line_id = l.line_id)
ORDER BY p.payment_id, abs(l.posted_on - p.paid_on), l.line_id
ON CONFLICT DO NOTHING;
SELECT m.payment_id, p.paid_on, l.posted_on, l.posted_on - p.paid_on AS days_apart,
p.amount_usd, m.kind
FROM matches AS m
JOIN payments AS p ON p.payment_id = m.payment_id
JOIN statement_lines AS l ON l.line_id = m.line_id
ORDER BY m.payment_id;
-- Check
SELECT CASE WHEN count(*) FILTER (WHERE kind = 'exact') = 4
AND count(*) FILTER (WHERE kind = 'near') = 3 THEN 'PASS' ELSE 'FAIL' END AS milestone_3
FROM matches;INSERT 0 4
INSERT 0 3
payment_id | paid_on | posted_on | days_apart | amount_usd | kind
------------+------------+------------+------------+------------+-------
1 | 2025-08-28 | 2025-08-29 | 1 | 450.00 | near
2 | 2025-10-30 | 2025-10-30 | 0 | 250.00 | exact
3 | 2025-12-03 | 2025-12-05 | 2 | 250.00 | near
4 | 2025-12-29 | 2025-12-29 | 0 | 550.00 | exact
5 | 2026-01-05 | 2026-01-06 | 1 | 200.00 | near
6 | 2025-11-14 | 2025-11-14 | 0 | 225.00 | exact
7 | 2025-12-19 | 2025-12-19 | 0 | 225.00 | exact
(7 rows)
milestone_3
-------------
PASS
(1 row)Explanation: Exact matches go first, because they're certain. The near query only considers payments and lines not yet matched (NOT EXISTS, EXISTS), and DISTINCT ON (p.payment_id) ... ORDER BY ... abs(days) picks each payment's closest line (SELECT DISTINCT). If two payments ever reach for the same line, ON CONFLICT DO NOTHING lets the unique key on line_id keep just one (Upsert and MERGE). Payments 1, 3 and 5 arrived at the bank one or two days after they were recorded, which is normal for card settlements and mailed checks.
Milestone 4: Identify Exceptions
Deliverable: one report listing everything that didn't match, from both sides.
Show solution
-- (Milestone 3, so there are matches to compare against)
INSERT INTO matches
SELECT p.payment_id, l.line_id, 'exact', DATE '2026-01-08'
FROM payments p JOIN statement_lines l ON l.amount_usd = p.amount_usd AND l.posted_on = p.paid_on
ON CONFLICT DO NOTHING;
INSERT INTO matches
SELECT DISTINCT ON (p.payment_id) p.payment_id, l.line_id, 'near', DATE '2026-01-08'
FROM payments p JOIN statement_lines l
ON l.amount_usd = p.amount_usd AND abs(l.posted_on - p.paid_on) <= 3
WHERE NOT EXISTS (SELECT 1 FROM matches m WHERE m.payment_id = p.payment_id)
AND NOT EXISTS (SELECT 1 FROM matches m WHERE m.line_id = l.line_id)
ORDER BY p.payment_id, abs(l.posted_on - p.paid_on), l.line_id
ON CONFLICT DO NOTHING;
-- The exception report
SELECT 'payment not in bank' AS exception, p.payment_id AS id, p.paid_on AS on_date,
p.amount_usd, NULL AS description
FROM payments AS p
LEFT JOIN matches AS m ON m.payment_id = p.payment_id
WHERE m.payment_id IS NULL
UNION ALL
SELECT CASE WHEN l.amount_usd < 0 THEN 'bank fee' ELSE 'deposit not recorded' END,
l.line_id, l.posted_on, l.amount_usd, l.description
FROM statement_lines AS l
LEFT JOIN matches AS m ON m.line_id = l.line_id
WHERE m.line_id IS NULL
ORDER BY on_date, id;INSERT 0 4
INSERT 0 3
exception | id | on_date | amount_usd | description
----------------------+----+------------+------------+--------------------------
bank fee | 8 | 2026-01-02 | -12.00 | MONTHLY SERVICE FEE
deposit not recorded | 10 | 2026-01-07 | 1450.00 | CARD DEPOSIT ANAMANENI A
(2 rows)Explanation: Each half is an anti-join: LEFT JOIN ... WHERE m.payment_id IS NULL keeps rows with no match (LEFT JOIN). UNION ALL stacks the two halves into one report with the same columns (UNION and UNION ALL). Every payment matched, so the first half is empty; the bank's side has two exceptions. The $12.00 fee is real money spent that the Fee Tracker doesn't track; the $1,450.00 deposit from "ANAMANENI A" is money received without a recorded payment, probably Advitha paying for her two courses, which someone should record. A reconciliation's value is exactly in finding lines like these.
Milestone 5: Post Matches in a Transaction
Deliverable: matching runs all-or-nothing; a forced failure part way through leaves no matches at all.
Show solution
BEGIN;
INSERT INTO matches
SELECT p.payment_id, l.line_id, 'exact', DATE '2026-01-08'
FROM payments p JOIN statement_lines l ON l.amount_usd = p.amount_usd AND l.posted_on = p.paid_on
ON CONFLICT DO NOTHING;
-- A forced failure: a match to a statement line that doesn't exist
INSERT INTO matches VALUES (1, 999, 'near', DATE '2026-01-08');
COMMIT;
-- Check: nothing was posted
SELECT CASE WHEN count(*) = 0 THEN 'PASS' ELSE 'FAIL' END AS milestone_5,
count(*) AS matches_after_failure
FROM matches;BEGIN
INSERT 0 4
ERROR: insert or update on table "matches" violates foreign key constraint "matches_line_id_fkey"
DETAIL: Key (line_id)=(999) is not present in table "statement_lines".
ROLLBACK
milestone_5 | matches_after_failure
-------------+-----------------------
PASS | 0
(1 row)Explanation: The first INSERT added the 4 exact matches inside the transaction. The second broke the foreign key to statement_lines, which aborted the transaction, so COMMIT became ROLLBACK and the 4 exact matches disappeared too (Transactions). Without the transaction, the month would be half reconciled, and running the job again would have to cope with that.
Milestone 6: Audit History and Permissions
Deliverable: every insert or delete in matches is logged with who did it and when; an accountant role can read the results but not change them.
Show solution
CREATE TABLE match_log (
log_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
action TEXT NOT NULL,
payment_id INTEGER NOT NULL,
line_id INTEGER NOT NULL,
done_by TEXT NOT NULL DEFAULT current_user,
done_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE FUNCTION log_match() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
IF TG_OP = 'INSERT' THEN
INSERT INTO match_log (action, payment_id, line_id) VALUES ('match', NEW.payment_id, NEW.line_id);
ELSE
INSERT INTO match_log (action, payment_id, line_id) VALUES ('unmatch', OLD.payment_id, OLD.line_id);
END IF;
RETURN NULL;
END $$;
CREATE TRIGGER matches_log AFTER INSERT OR DELETE ON matches
FOR EACH ROW EXECUTE FUNCTION log_match();
CREATE ROLE accountant;
GRANT SELECT ON matches, statement_lines, payments, match_log TO accountant;
INSERT INTO matches
SELECT p.payment_id, l.line_id, 'exact', DATE '2026-01-08'
FROM payments p JOIN statement_lines l ON l.amount_usd = p.amount_usd AND l.posted_on = p.paid_on;
DELETE FROM matches WHERE payment_id = 7;
SELECT log_id, action, payment_id, line_id, done_by FROM match_log ORDER BY log_id;
SET ROLE accountant;
SELECT count(*) AS accountant_can_read FROM matches;
DELETE FROM matches WHERE payment_id = 2;CREATE TABLE
CREATE FUNCTION
CREATE TRIGGER
CREATE ROLE
GRANT
INSERT 0 4
DELETE 1
log_id | action | payment_id | line_id | done_by
--------+---------+------------+---------+----------
1 | match | 6 | 3 | postgres
2 | match | 7 | 5 | postgres
3 | match | 2 | 2 | postgres
4 | match | 4 | 6 | postgres
5 | unmatch | 7 | 5 | postgres
(5 rows)
SET
accountant_can_read
---------------------
3
(1 row)
ERROR: permission denied for table matchesExplanation: The trigger writes one log row per matched or unmatched pair, including who did it (current_user) and when (Triggers). The log shows four matches and then payment 7 being unmatched. The accountant role can read matches but its DELETE is refused, because only SELECT was granted (Users, Roles and Privileges). The done_at column is left out of the output because it changes every run.
Milestone 7: Optimize the Queries
Deliverable: indexes that let the matching join find candidate lines by amount and date instead of scanning every line.
Show solution
CREATE INDEX statement_lines_amount_posted_idx ON statement_lines (amount_usd, posted_on);
SET enable_seqscan = off; -- the table is tiny; force the planner to show the index it would use
-- The lookup the matching join makes for one payment: 250.00, paid 2025-12-03
EXPLAIN (COSTS OFF)
SELECT line_id
FROM statement_lines
WHERE amount_usd = 250.00
AND posted_on BETWEEN DATE '2025-12-03' - 3 AND DATE '2025-12-03' + 3;CREATE INDEX
SET
QUERY PLAN
-------------------------------------------------------------------------------------------------------------------
Index Scan using statement_lines_amount_posted_idx on statement_lines
Index Cond: ((amount_usd = 250.00) AND (posted_on >= '2025-11-30'::date) AND (posted_on <= '2025-12-06'::date))
(2 rows)Explanation: The matching join looks up lines by amount with equality and date with a range, so the index puts amount_usd first and posted_on second (Index Design). The plan shows one index search that uses both conditions at once: amount_usd = 250.00 and the date range, so only the candidate lines are read. Rewriting abs(l.posted_on - p.paid_on) <= 3 as BETWEEN p.paid_on - 3 AND p.paid_on + 3 matters: an index can't be used for a condition wrapped around the column in a function, but it can for a plain range (Writing Fast Queries). With 9 lines, PostgreSQL would normally just scan the table, which is why enable_seqscan = off is used here only to show the plan; never set it in production.
Milestone 8: Build and Test the Application
Deliverable: a Python program that runs the monthly reconciliation with parameters, plus tests that pass against a fresh database (SQL from Python, Testing SQL). The matching SQL now takes the date and the window as parameters, and the near query uses the same exact-then-near order:
"""Monthly reconciliation: match Fee Tracker payments to bank statement lines."""
import os
from datetime import date
import psycopg
CONNINFO = "host=localhost port=5432 dbname=feetracker user=fee_app"
EXACT = """
INSERT INTO matches (payment_id, line_id, kind, matched_on)
SELECT p.payment_id, l.line_id, 'exact', %(as_of)s
FROM payments AS p
JOIN statement_lines AS l
ON l.amount_usd = p.amount_usd AND l.posted_on = p.paid_on
WHERE NOT EXISTS (SELECT 1 FROM matches m WHERE m.payment_id = p.payment_id)
AND NOT EXISTS (SELECT 1 FROM matches m WHERE m.line_id = l.line_id)
ON CONFLICT DO NOTHING
"""
NEAR = """
INSERT INTO matches (payment_id, line_id, kind, matched_on)
SELECT DISTINCT ON (p.payment_id) p.payment_id, l.line_id, 'near', %(as_of)s
FROM payments AS p
JOIN statement_lines AS l
ON l.amount_usd = p.amount_usd
AND abs(l.posted_on - p.paid_on) <= %(days)s
WHERE NOT EXISTS (SELECT 1 FROM matches m WHERE m.payment_id = p.payment_id)
AND NOT EXISTS (SELECT 1 FROM matches m WHERE m.line_id = l.line_id)
ORDER BY p.payment_id, abs(l.posted_on - p.paid_on), l.line_id
ON CONFLICT DO NOTHING
"""
UNMATCHED_LINES = """
SELECT l.line_id FROM statement_lines AS l
WHERE NOT EXISTS (SELECT 1 FROM matches m WHERE m.line_id = l.line_id)
ORDER BY l.line_id
"""
def reconcile(conn, as_of, days=3):
"""Matches exact pairs first, then near ones; all or nothing."""
with conn.transaction():
exact = conn.execute(EXACT, {"as_of": as_of}).rowcount
near = conn.execute(NEAR, {"as_of": as_of, "days": days}).rowcount
unmatched = [line_id for (line_id,) in conn.execute(UNMATCHED_LINES)]
return {"exact": exact, "near": near, "unmatched_lines": unmatched}
if __name__ == "__main__":
with psycopg.connect(CONNINFO, password=os.environ["FEE_DB_PASSWORD"],
autocommit=True) as conn:
print("first run: ", reconcile(conn, date(2026, 1, 8)))
print("second run:", reconcile(conn, date(2026, 1, 8)))first run: {'exact': 4, 'near': 3, 'unmatched_lines': [8, 10]}
second run: {'exact': 0, 'near': 0, 'unmatched_lines': [8, 10]}Explanation: Both inserts run inside conn.transaction(), so a failure rolls back the whole run (milestone 5). Running the job a second time adds nothing, because the NOT EXISTS conditions skip what's already matched: the job is idempotent, safe to rerun after a crash. The values travel as parameters (%(as_of)s, %(days)s), never pasted into the SQL. And the tests:
import os
from datetime import date
import psycopg
import pytest
from reconcile import CONNINFO, reconcile
AS_OF = date(2026, 1, 8)
@pytest.fixture
def conn():
"""Each test runs in a transaction that is rolled back afterwards."""
with psycopg.connect(CONNINFO,
password=os.environ["FEE_DB_PASSWORD"]) as c:
with c.transaction(force_rollback=True):
yield c
def test_exact_and_near_matches(conn):
result = reconcile(conn, AS_OF)
assert (result["exact"], result["near"]) == (4, 3)
def test_every_payment_is_matched(conn):
reconcile(conn, AS_OF)
left = conn.execute(
"SELECT count(*) FROM payments p WHERE NOT EXISTS"
" (SELECT 1 FROM matches m WHERE m.payment_id = p.payment_id)"
).fetchone()[0]
assert left == 0
def test_bank_fee_and_unknown_deposit_are_exceptions(conn):
assert reconcile(conn, AS_OF)["unmatched_lines"] == [8, 10]
def test_running_twice_adds_nothing(conn):
reconcile(conn, AS_OF)
again = reconcile(conn, AS_OF)
assert (again["exact"], again["near"]) == (0, 0)
def test_narrow_window_leaves_late_lines(conn):
result = reconcile(conn, AS_OF, days=1)
assert result["near"] == 2 # the 2-day gap is too wide============================= test session starts ==============================
collecting ... collected 5 items
test_reconcile.py::test_exact_and_near_matches PASSED [ 20%]
test_reconcile.py::test_every_payment_is_matched PASSED [ 40%]
test_reconcile.py::test_bank_fee_and_unknown_deposit_are_exceptions PASSED [ 60%]
test_reconcile.py::test_running_twice_adds_nothing PASSED [ 80%]
test_reconcile.py::test_narrow_window_leaves_late_lines PASSED [100%]
============================== 5 passed in 0.06s ===============================Explanation: Each test runs in a transaction that is rolled back, so every test starts from the same unmatched data. The last test shows why the window is a parameter: with 1 day instead of 3, payment 3, which reached the bank 2 days later, isn't matched.
Milestone 9: Back Up and Restore
Deliverable: a backup of the reconciliation tables, a restore into a new database, and a check that the copy matches the original. On your own server, the backup and restore are two commands (Backup and Restore):
pg_dump --format=custom --table=statement_lines --table=matches --table=match_log \
--file=reconciliation-2026-01.dump feetracker
createdb feetracker_restore_test
pg_restore --dbname=feetracker_restore_test reconciliation-2026-01.dumpThe check is SQL, and it's the part people skip. Run the same summary on both databases and compare. Here, a copy in a separate schema stands in for the restored database:
Show solution
INSERT INTO matches
SELECT p.payment_id, l.line_id, 'exact', DATE '2026-01-08'
FROM payments p JOIN statement_lines l ON l.amount_usd = p.amount_usd AND l.posted_on = p.paid_on;
-- Stand-in for the restored database
CREATE SCHEMA restored;
CREATE TABLE restored.statement_lines AS SELECT * FROM statement_lines;
CREATE TABLE restored.matches AS SELECT * FROM matches;
SELECT 'original' AS copy, (SELECT count(*) FROM statement_lines) AS lines,
(SELECT sum(amount_usd) FROM statement_lines) AS total_usd,
(SELECT count(*) FROM matches) AS matches
UNION ALL
SELECT 'restored', (SELECT count(*) FROM restored.statement_lines),
(SELECT sum(amount_usd) FROM restored.statement_lines),
(SELECT count(*) FROM restored.matches)
ORDER BY copy;
-- Check: every row in one copy is in the other
SELECT CASE WHEN NOT EXISTS (SELECT * FROM statement_lines EXCEPT SELECT * FROM restored.statement_lines)
AND NOT EXISTS (SELECT * FROM restored.statement_lines EXCEPT SELECT * FROM statement_lines)
AND NOT EXISTS (SELECT * FROM matches EXCEPT SELECT * FROM restored.matches)
AND NOT EXISTS (SELECT * FROM restored.matches EXCEPT SELECT * FROM matches)
THEN 'PASS' ELSE 'FAIL' END AS milestone_9;INSERT 0 4
CREATE SCHEMA
SELECT 9
SELECT 4
copy | lines | total_usd | matches
----------+-------+-----------+---------
original | 9 | 3588.00 | 4
restored | 9 | 3588.00 | 4
(2 rows)
milestone_9
-------------
PASS
(1 row)Explanation: Counts and totals agree, and comparing the rows with EXCEPT in both directions proves the copy is identical, not just the same size (Testing SQL). A backup that has never been restored and checked is only a hope.
Common Mistakes
Matching near before exact. A near match can take a line that belonged to an exact pair. Run the certain matches first.
Allowing one line to match two payments. Without the unique key on line_id, two $250.00 payments can claim the same deposit. Let the database enforce one-to-one.
Ignoring the bank's side. Checking only that each payment found a line misses fees and unrecorded deposits. Report unmatched rows from both sides.
Non-repeatable jobs. A job that matches again on a second run doubles the work or fails on keys. Make it idempotent with NOT EXISTS and ON CONFLICT DO NOTHING.
Functions around indexed columns. abs(posted_on - paid_on) <= 3 can't use an index; a BETWEEN range can.
Skipping the restore test. Restore, then compare counts, totals and rows.
Interview Corner
How would you reconcile payments against a bank statement in SQL?
Clean and load the statement, match exact pairs (same amount and date), then near pairs within a tolerance window among the unmatched rows, enforce one-to-one with keys on the matches table, and report unmatched rows from both sides as exceptions.
What makes a batch job idempotent, and why does it matter?
Running it again produces no extra changes: here, NOT EXISTS and ON CONFLICT DO NOTHING skip rows already matched. It lets you rerun a job safely after a failure.
How do you prove a restore worked?
Restore into a separate database, then compare row counts, totals and, for important tables, the rows themselves with EXCEPT in both directions.
Practice
Challenge: Write the month-end summary Srihitha signs off: the number and total of matched payments, and the number and total of exceptions on the bank's side, after running milestone 3's matching.
Show solution
INSERT INTO matches
SELECT p.payment_id, l.line_id, 'exact', DATE '2026-01-08'
FROM payments p JOIN statement_lines l ON l.amount_usd = p.amount_usd AND l.posted_on = p.paid_on
ON CONFLICT DO NOTHING;
INSERT INTO matches
SELECT DISTINCT ON (p.payment_id) p.payment_id, l.line_id, 'near', DATE '2026-01-08'
FROM payments p JOIN statement_lines l
ON l.amount_usd = p.amount_usd AND abs(l.posted_on - p.paid_on) <= 3
WHERE NOT EXISTS (SELECT 1 FROM matches m WHERE m.payment_id = p.payment_id)
AND NOT EXISTS (SELECT 1 FROM matches m WHERE m.line_id = l.line_id)
ORDER BY p.payment_id, abs(l.posted_on - p.paid_on), l.line_id
ON CONFLICT DO NOTHING;
SELECT count(m.payment_id) AS matched_payments,
sum(p.amount_usd) FILTER (WHERE m.payment_id IS NOT NULL) AS matched_usd,
(SELECT count(*) FROM statement_lines l
WHERE NOT EXISTS (SELECT 1 FROM matches x WHERE x.line_id = l.line_id)) AS exceptions,
(SELECT sum(amount_usd) FROM statement_lines l
WHERE NOT EXISTS (SELECT 1 FROM matches x WHERE x.line_id = l.line_id)) AS exceptions_usd
FROM payments AS p
LEFT JOIN matches AS m ON m.payment_id = p.payment_id;INSERT 0 4
INSERT 0 3
matched_payments | matched_usd | exceptions | exceptions_usd
------------------+-------------+------------+----------------
7 | 2150.00 | 2 | 1438.00
(1 row)All seven payments, $2,150.00, are matched. The two exceptions add up to $1,438.00: the $1,450.00 unrecorded deposit minus the $12.00 fee. As a final cross-check, matched plus exceptions should equal the statement's total: $2,150.00 + $1,438.00 = $3,588.00, the same total milestone 2 checked when the lines were loaded.
Key Takeaways
Was this tutorial helpful?