Project: Data Cleanup
In this project, you take a messy file from outside, the tutoring program's bank statement, and turn it into a clean, trustworthy table. Data from other systems is rarely tidy. Dates arrive in two formats, amounts come with dollar signs and commas, names have stray spaces, one line appears twice, and a few lines are simply broken. The professional way to handle this is to load everything as text into a staging table, inspect it, clean it with SQL, move only good rows into the real table, set bad rows aside with a reason, and add constraints so bad data can't sneak in again. The cleaned statement is what the capstone, Capstone: Fee Tracker Payment Reconciliation, matches against the Fee Tracker's payments.
In One Minute
- Stage first: load the file into a table where every column is
TEXT, so nothing is refused on the way in. - Profile: count each kind of problem before fixing anything.
- Clean with SQL:
trim,upper,regexp_replace,to_date,pg_input_is_validandreplace. - Deduplicate with
ROW_NUMBER()and keep one copy of each line. - Reject, don't drop: keep bad rows in a rejects table with the reason.
- Lock it down: the clean table gets types,
NOT NULLandCHECKconstraints. - Data in Try it: examples marked with the bank-statement dataset load
bank-statement.sqlfirst.
Step 1: Stage the File
A staging table accepts the file exactly as it is: every column is text, with no constraints. If the real table were loaded directly, the first bad date would stop the whole load. On your own server, you'd load the bank's CSV file with psql's \copy (INSERT INTO SELECT and Loading Files covers COPY):
\copy statement_raw (posted, description, amount) FROM 'statement.csv' WITH (FORMAT csv, HEADER true)Try it can't read files from your computer, so the bank-statement dataset already holds the twelve lines of that file in statement_raw. Look at them first:
SELECT line_no, posted, description, amount
FROM statement_raw
ORDER BY line_no; line_no | posted | description | amount
---------+------------+-----------------------------+-----------
1 | 2025-08-29 | CARD DEPOSIT ANAMANENI S | 450.00
2 | 10/30/2025 | card deposit anamaneni s | $250.00
3 | 2025-11-14 | Card Deposit Anamaneni N | 225.00
4 | 2025-12-05 | CHECK 1042 ANAMANENI | 250.00
5 | 2025-12-19 | CHECK 1043 ANAMANENI | 225
6 | 2025-12-29 | CARD DEPOSIT ANAMANENI S | 550.00
7 | 2025-12-29 | CARD DEPOSIT ANAMANENI S | 550.00
8 | 2026-01-02 | MONTHLY SERVICE FEE | -12.00
9 | 2026-01-06 | DEPOSIT | 200.00
10 | 2026-01-07 | CARD DEPOSIT ANAMANENI A | $1,450.00
11 | 2026-13-01 | DEPOSIT | 100.00
12 | | TRANSFER |
(12 rows)Explanation: Twelve lines, and plenty wrong with them: line 2 uses a US date and a dollar sign; line 3 has extra spaces and mixed case; line 5 has no cents; lines 6 and 7 are identical; line 10 has a comma in the amount; line 11's month is 13; line 12 is empty. Each problem is easy to fix by hand in twelve lines, but the bank sends a new file every month, so the fixes have to be SQL that can run again.
Step 2: Profile the Problems
Before fixing anything, measure. A profile query counts each kind of problem, so you know what the cleanup has to handle and can check later that it handled all of it:
SELECT
count(*) AS lines,
count(*) FILTER (WHERE posted ~ '^\d{4}-\d{2}-\d{2}$') AS iso_dates,
count(*) FILTER (WHERE posted ~ '^\d{1,2}/\d{1,2}/\d{4}$') AS us_dates,
count(*) FILTER (WHERE coalesce(trim(posted), '') = '') AS missing_dates,
count(*) FILTER (WHERE amount ~ '[$,]') AS amounts_with_symbols,
count(*) FILTER (WHERE coalesce(trim(amount), '') = '') AS missing_amounts,
count(*) FILTER (WHERE description <> upper(trim(description))) AS messy_text
FROM statement_raw; lines | iso_dates | us_dates | missing_dates | amounts_with_symbols | missing_amounts | messy_text
-------+-----------+----------+---------------+----------------------+-----------------+------------
12 | 10 | 1 | 1 | 2 | 1 | 2
(1 row)Explanation: FILTER (WHERE ...) counts only the rows that match each test (Pivoting Data), and ~ matches a regular expression: ^\d{4}-\d{2}-\d{2}$ means "exactly four digits, a dash, two digits, a dash, two digits". Ten dates look like ISO dates (one of them, 2026-13-01, is still impossible), one is in US format and one is missing; two amounts have $ or commas, one is missing; and two descriptions need trimming or upper-casing.
Step 3: Clean Each Column
Clean each column with an expression that turns valid text into the right type, and anything else into NULL. NULL then marks the rows to reject.
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
ORDER BY line_no; line_no | posted_on | description | amount_usd
---------+------------+--------------------------+------------
1 | 2025-08-29 | CARD DEPOSIT ANAMANENI S | 450.00
2 | 2025-10-30 | CARD DEPOSIT ANAMANENI S | 250.00
3 | 2025-11-14 | CARD DEPOSIT ANAMANENI N | 225.00
4 | 2025-12-05 | CHECK 1042 ANAMANENI | 250.00
5 | 2025-12-19 | CHECK 1043 ANAMANENI | 225.00
6 | 2025-12-29 | CARD DEPOSIT ANAMANENI S | 550.00
7 | 2025-12-29 | CARD DEPOSIT ANAMANENI S | 550.00
8 | 2026-01-02 | MONTHLY SERVICE FEE | -12.00
9 | 2026-01-06 | DEPOSIT | 200.00
10 | 2026-01-07 | CARD DEPOSIT ANAMANENI A | 1450.00
11 | NULL | DEPOSIT | 100.00
12 | NULL | TRANSFER | NULL
(12 rows)Explanation:
| Column | Cleaning | Why |
|---|---|---|
| Date | ISO text is cast to date only if pg_input_is_valid says it can be; US text is read with to_date(posted, 'MM/DD/YYYY') | pg_input_is_valid (PostgreSQL 16 and later) tests a value without raising an error, so 2026-13-01 becomes NULL instead of stopping the query (Type Conversion) |
| Description | trim, then collapse runs of spaces with regexp_replace(..., '\s+', ' ', 'g'), then upper | The same payer always looks the same (String Functions) |
| Amount | Remove $ and ,, check it's a number, cast to numeric and round to cents | $1,450.00 becomes 1450.00; 225 becomes 225.00 |
Always parse dates with an explicit format. PostgreSQL would also read '10/30/2025'::date correctly here, but only because the server's DateStyle setting is MDY. On a server set to DMY, the same text means the 10th day of the 30th month and fails, and '03/04/2025' silently becomes April 3 instead of March 4 (Dates and Times). to_date with a format behaves the same on every server.
Step 4: Remove Duplicates and Reject Bad Rows
A duplicate is two lines with the same date, description and amount; keep the first. ROW_NUMBER() numbers the copies inside each group, so copy 1 stays and later copies go (Ranking Functions). Then split the rows into good and bad:
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 statement_rejects (
line_no INTEGER PRIMARY KEY,
reason TEXT NOT NULL
);
CREATE TEMP TABLE 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;
-- Bad rows, with the reason
INSERT INTO statement_rejects
SELECT line_no,
CASE WHEN posted_on IS NULL THEN 'unreadable date' ELSE 'unreadable amount' END
FROM cleaned
WHERE posted_on IS NULL OR amount_usd IS NULL;
-- Good rows, first copy of each
INSERT INTO statement_lines (line_id, account_id, posted_on, description, amount_usd)
SELECT line_no, 1, posted_on, description, amount_usd
FROM (
SELECT c.*, ROW_NUMBER() OVER (PARTITION BY posted_on, description, amount_usd
ORDER BY line_no) AS copy
FROM cleaned AS c
WHERE posted_on IS NOT NULL AND amount_usd IS NOT NULL
) AS numbered
WHERE copy = 1;
SELECT (SELECT count(*) FROM statement_raw) AS raw_lines,
(SELECT count(*) FROM statement_lines) AS loaded,
(SELECT count(*) FROM statement_rejects) AS rejected;
SELECT line_no, reason FROM statement_rejects ORDER BY line_no;CREATE TABLE
CREATE TABLE
SELECT 12
INSERT 0 2
INSERT 0 9
raw_lines | loaded | rejected
-----------+--------+----------
12 | 9 | 2
(1 row)
line_no | reason
---------+-----------------
11 | unreadable date
12 | unreadable date
(2 rows)Explanation: Twelve raw lines became 9 loaded lines and 2 rejects, and the twelfth, line 7, was dropped as a duplicate of line 6. The counts must always add up: loaded + rejected + duplicates = raw lines (9 + 2 + 1 = 12). Checking that sum after every load is the quickest way to notice that a cleanup rule silently lost rows. Rejects keep their line number and reason, so someone can fix them at the source, the bank or the export, rather than the data disappearing without a trace.
Step 5: Lock It Down
The clean table's constraints are the guarantee that bad data can't return, whether it comes from next month's file or from someone typing a row by hand. Each problem we cleaned maps to a rule:
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 CHECK (description = upper(trim(description))),
amount_usd NUMERIC(10,2) NOT NULL CHECK (amount_usd <> 0)
);
INSERT INTO statement_lines VALUES (1, 1, '2026-13-01', 'DEPOSIT', 100.00);
INSERT INTO statement_lines VALUES (2, 1, '2026-01-08', ' Deposit', 100.00);
INSERT INTO statement_lines VALUES (3, 1, '2026-01-08', 'DEPOSIT', NULL);
INSERT INTO statement_lines VALUES (4, 1, '2026-01-08', 'DEPOSIT', 100.004);
SELECT line_id, amount_usd FROM statement_lines;CREATE TABLE
ERROR: date/time field value out of range: "2026-13-01"
HINT: Perhaps you need a different "DateStyle" setting.
ERROR: new row for relation "statement_lines" violates check constraint "statement_lines_description_check"
DETAIL: Failing row contains (2, 1, 2026-01-08, Deposit, 100.00).
ERROR: null value in column "amount_usd" of relation "statement_lines" violates not-null constraint
DETAIL: Failing row contains (3, 1, 2026-01-08, DEPOSIT, null).
INSERT 0 1
line_id | amount_usd
---------+------------
4 | 100.00
(1 row)Explanation: The DATE type refuses month 13. The CHECK refuses untrimmed, lower-case text. NOT NULL refuses a missing amount. The last insert succeeds: NUMERIC(10,2) rounds 100.004 to 100.00 rather than refusing it, which is worth knowing; if extra decimals should be an error, compare the value with round(amount_usd, 2) in a CHECK before the column type rounds it, or validate in the cleaning step as we did.
| Problem in the file | Guard in the clean table |
|---|---|
| Impossible or missing date | posted_on DATE NOT NULL |
$, commas, text in amounts | NUMERIC(10,2) type |
| Missing amount, zero amount | NOT NULL, CHECK (amount_usd <> 0) |
| Spaces and mixed case | CHECK (description = upper(trim(description))) |
| Unknown account | REFERENCES bank_accounts |
Common Mistakes
Loading straight into the real table. One bad value stops the load, or worse, a lenient column type accepts garbage. Stage as text first.
Fixing data by hand in the database. Next month's file has the same problems. Put every fix in SQL that runs on each load.
Relying on DateStyle to read dates. Use to_date with an explicit format.
Dropping bad rows silently. Keep them with a reason, and check that loaded + rejected + duplicates equals the raw count.
Deduplicating on contents when an id exists. Two real payments can look identical. Use the source's transaction id when there is one.
Casting with ::numeric on unchecked text. One bad value raises an error for the whole query. Check with pg_input_is_valid first, or clean the text so it can only be a number.
Interview Corner
Why load external data into a staging table first?
So the load never fails on bad values: everything arrives as text. Then SQL can profile and clean it, move good rows into typed, constrained tables, and keep bad rows aside with a reason.
How do you remove duplicate rows but keep one copy?
Number the copies with ROW_NUMBER() OVER (PARTITION BY the columns that define a duplicate ORDER BY something stable) and keep only row number 1, or delete the rest.
How do you convert text to a date safely when some values are invalid?
Check first, then convert: in PostgreSQL 16+, pg_input_is_valid(text, 'date'); for other formats, match a pattern and use to_date(text, 'MM/DD/YYYY'). Invalid values become NULL and are rejected with a reason.
How do you make sure a load didn't lose rows?
Reconcile the counts: rows loaded plus rows rejected plus duplicates removed must equal the rows in the source file.
Practice
Challenge: After the cleanup, the treasurer wants a monthly summary of the clean statement: deposits (positive amounts) and fees (negative amounts) for each month, from the statement lines you loaded. Use the bank-statement dataset and repeat the load in a compact form.
Show solution
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
),
good AS (
SELECT DISTINCT ON (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
)
SELECT to_char(posted_on, 'YYYY-MM') AS month,
sum(amount_usd) FILTER (WHERE amount_usd > 0) AS deposits_usd,
coalesce(sum(amount_usd) FILTER (WHERE amount_usd < 0), 0) AS fees_usd
FROM good
GROUP BY month
ORDER BY month; month | deposits_usd | fees_usd
---------+--------------+----------
2025-08 | 450.00 | 0
2025-10 | 250.00 | 0
2025-11 | 225.00 | 0
2025-12 | 1025.00 | 0
2026-01 | 1650.00 | -12.00
(5 rows)DISTINCT ON (...) is PostgreSQL's shorthand for "first row of each group", another way to drop the duplicate (SELECT DISTINCT). The $12.00 service fee shows up in January 2026; every other line is a deposit. December's $1,025.00 counts the $550.00 deposit once, not twice.
Key Takeaways
Was this tutorial helpful?