Quick revision
The short answer
The ROW_NUMBER window sorts all 400 million rows by email and time, and that sort spills to temporary files far larger than work_mem; deleting most of the rows in place then adds bloat and WAL on top. I would build a new clean table with DISTINCT ON (customer_email) ... ORDER BY customer_email, updated_at DESC, processing in chunks by email range or hash so each sort fits, and swap it in. An index on (customer_email, updated_at DESC) can provide presorted input, and the real fix is a unique constraint with an upsert on load so duplicates never form.
What to remember
In this answer, we saw that deduplicating 400 million rows with one ROW_NUMBER window and a DELETE forces a sort of the whole table that spills far beyond work_mem, and then a huge delete that adds WAL and bloat. We measured the spill with EXPLAIN (ANALYZE, BUFFERS), processed the table in hash chunks, built a clean table with DISTINCT ON and swapped it in, considered an index on (customer_email, updated_at DESC) for presorted input, and stopped duplicates at the source with a unique constraint and an upsert.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
The ROW_NUMBER window sorts all 400 million rows by email and time, and that sort spills to temporary files far larger than work_mem; deleting most of the rows in place then adds bloat and WAL on top. I would build a new clean table with DISTINCT ON (customer_email) ... ORDER BY customer_email, updated_at DESC, processing in chunks by email range or hash so each sort fits, and swap it in. An index on (customer_email, updated_at DESC) can provide presorted input, and the real fix is a unique constraint with an upsert on load so duplicates never form.
Why this question is asked
Deduplication jobs often start life on a small table, where any approach works, and then fail one night when the table has grown a hundredfold. The failure here, running out of temp space, is a clear signal about what the database is doing internally. Interviewers ask this scenario to see whether we can read that signal, measure it, and change the approach rather than just asking for a bigger disk. In this answer, we will see why the window query needs so much temporary space, measure it, restructure the job into chunks, replace the in-place delete with a rebuild and swap, look at the role of an index, and finally stop duplicates at the source.
1Why the Window Needs So Much Temp Space
The job probably looks like this: compute a row number per email, newest first, and delete every row whose number is greater than 1.
To number rows within each email in updated_at order, PostgreSQL must see all rows of an email together and in order. Without a suitable index, it sorts the whole table by (customer_email, updated_at DESC). Each sort may use work_mem of memory, a per-operation limit that is often 4 MB to 64 MB, and anything beyond that is written to temporary files as an external merge sort. Sorting 400 million rows, even with only the email, timestamp and row pointer, means tens of gigabytes of temp files, and the DELETE then needs a hash or merge join between those results and the table, which can spill again.
So the problem is not ROW_NUMBER itself. It is one giant sort plus one giant delete, both in a single statement.
2Measuring It First
Before changing anything, we confirm where the space goes. EXPLAIN (ANALYZE, BUFFERS) on a sample, say one email prefix, shows the sort method and how much it spilled. In production, setting log_temp_files = 0 makes PostgreSQL log every temporary file with its size, and pg_stat_database.temp_bytes shows the running total.
The words external merge and the Disk figure tell us the sort did not fit in memory. If one letter of the alphabet needs 1.8 GB of temp space, the whole table needs many times that. Raising work_mem for this session, SET work_mem = '1GB', makes each sort faster but cannot make a sort of the full table fit, so we also need to change the shape of the job.
3Processing in Chunks
The first change is to process a slice of emails at a time. Every duplicate of an email is in the same slice, so each slice can be deduplicated on its own, and its sort is small enough to fit in memory or at least in modest temp space. A slice can be an email range, or a hash bucket so slices have similar sizes.
hashtext is an internal PostgreSQL function that is stable within a version but not documented as a public API, so some teams prefer md5(customer_email) or a range on the email text instead. Either way, each chunk runs in its own transaction, so a failure only repeats one chunk, and the job can report progress.
4Rebuild and Swap Instead of Deleting in Place
Deleting in place is the wrong tool when a large share of the rows are duplicates. A DELETE writes every removed row to the WAL, the write-ahead log that replicas replay, leaves dead rows that VACUUM must clean, and does not give the space back to the operating system. If 300 million of the 400 million rows go, it is much cheaper to copy the 100 million rows we keep into a new table and swap.
PostgreSQL's DISTINCT ON is made for keeping one row per key. DISTINCT ON (customer_email) keeps the first row of each email in the ORDER BY order, so ordering by updated_at DESC keeps the newest.
- Measure the spillEXPLAIN (ANALYZE, BUFFERS), log_temp_files
- Create an empty clean tableunlogged during the load
- Copy one hash bucket with DISTINCT ONnewest row per email
- All 64 buckets done?YesAdd the unique indexNoCopy the next bucket
- Compare counts and sample rowsdistinct emails = rows in clean table
- Swap names in one short transactionthen drop the old table later
6 steps in order. Play them, or step through them one at a time.
Notice the extra id DESC: if two rows of the same email have the same updated_at, the result would otherwise be arbitrary. An unlogged table skips WAL during the load, which makes it much faster; SET LOGGED then writes it once, and if replicas need it the cost is paid there. The rename is a quick metadata change, but it needs a brief exclusive lock, and views, foreign keys and grants that pointed to the old table must be recreated, so we script and test the swap.
5Can an Index Avoid the Sort?
An index on (customer_email, updated_at DESC) stores entries in exactly the order the window or DISTINCT ON needs. With it, PostgreSQL can read rows presorted and skip the sort. But building that index on 400 million rows is itself one large sort, using maintenance_work_mem and temp space, and reading the table in index order means random heap reads. So for a one-off cleanup the index rarely pays off; for a recurring job, or for the final clean table where we need a unique index anyway, it does.
6Fixing the Source
Duplicates exist because the load process inserts every version of a customer as a new row. If staging had a unique constraint on customer_email and the loader used an upsert, there would be nothing to deduplicate.
The WHERE in the DO UPDATE clause matters: a late, older record must not overwrite a newer one. If the loader needs to keep history, the history goes to a separate table, and staging keeps only the current row per email. One more check is normalisation: if 'Ann@x.com' and 'ann@x.com' should be the same customer, the unique key should be on lower(customer_email), or the column should use a case-insensitive type.
7Follow-up questions
Why not just raise work_mem to 10 GB for the job?
work_mem applies per sort or hash operation, and a query can run several such operations and parallel workers each with their own allowance, so a large value can exhaust the server's memory. And a sort of 400 million wide rows can exceed even 10 GB. A session-level increase to a few hundred megabytes combined with chunking is safer and gives predictable resource use.
How do you check the result is correct before swapping?
Compare SELECT count(DISTINCT customer_email) FROM staging with SELECT count(*) FROM staging_clean, which must match, and spot-check a sample of emails to confirm the kept row has the maximum updated_at. Running both checks per bucket during the load catches problems early.
What if the table must stay online for writes during the cleanup?
Then the rebuild needs to capture changes made during the copy, for example with a trigger that writes changed emails to a side table and a final catch-up pass before the swap. An alternative is chunked in-place deletes with short transactions and pauses, which is slower and leaves bloat, but keeps the table in place.
8Conclusion
In this answer, we saw that deduplicating 400 million rows with one ROW_NUMBER window and a DELETE forces a sort of the whole table that spills far beyond work_mem, and then a huge delete that adds WAL and bloat. We measured the spill with EXPLAIN (ANALYZE, BUFFERS), processed the table in hash chunks, built a clean table with DISTINCT ON and swapped it in, considered an index on (customer_email, updated_at DESC) for presorted input, and stopped duplicates at the source with a unique constraint and an upsert.
Open with
The ROW_NUMBER window has to sort the whole table by email and updated_at to number the rows, and with 400 million rows that sort spills far beyond work_mem into temp files, and then the DELETE joins against the result and spills again.
Then, if they want more
I'd confirm it with EXPLAIN ANALYZE BUFFERS on a slice, which shows an external merge sort with the disk size, and with log_temp_files. Then I'd change the approach rather than buy disk.
First, chunk the work by a hash or range of email, since all duplicates of an email fall in the same chunk, so each sort is small and each chunk is its own transaction.
Second, instead of deleting most of the rows in place, which generates huge WAL and bloat, I'd build a new table with SELECT DISTINCT ON (customer_email) star ordered by email, updated_at descending and id as a tiebreaker, add a unique index, verify the counts, and swap the names in a short transaction.
An index on email and updated_at descending would give presorted input, which helps for a recurring job. And the real fix is at the source: a unique constraint on email and an INSERT ON CONFLICT DO UPDATE that only overwrites when the incoming row is newer, so duplicates never form.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- PostgreSQL documentation, The SQL Language
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "A deduplication job keeps the latest row per customer_email from a 400 million row...": https://scrivio-interview-library.netlify.app/databases/advanced-sql/7e06750702/