Scrivio Interview library
CodingIntermediate7 min read · updated 12 November 2026

You migrated customers from a legacy table old_customers(email, name) to customers(email, name). Write queries to find rows missing in the new table, extra rows, and rows whose name differs, and say how you would run this on 80 million rows.

Rows missing from the new table are old_customers EXCEPT customers, and extra rows are the reverse. Changed names are found more clearly by joining on email and comparing names with IS DISTINCT FROM, which handles NULLs. On 80 million rows we compare hashes per key bucket first, drill into only the buckets that differ, and run everything on a replica or snapshot so both sides are read at one consistent point in time.

Why this question is asked

Every data migration ends with the same question: did everything arrive, and did it arrive unchanged? A migration that looks finished can still have lost rows to a filter, duplicated rows on a retry, or changed values through a trimming or encoding step. Interviewers ask this because it tests both SQL, in particular set operations and NULL handling, and judgement about running heavy comparisons on big tables without hurting production. In this answer, we will write the three comparison queries, see why EXCEPT alone gives confusing output for changed rows, handle NULLs correctly, and then scale the check to 80 million rows with bucketed hashes on a consistent snapshot.

1A Quick Recap of the Tools

EXCEPT returns the distinct rows of the first query that do not appear in the second, comparing entire rows column by column. It is the most direct way to ask which rows exist on one side only.

IS DISTINCT FROM is a comparison that treats NULL as an ordinary value. The usual a <> b returns unknown when either side is NULL, so a row whose old name was NULL and whose new name is 'Ana' would never be reported as changed. a IS DISTINCT FROM b returns true there, and returns false when both sides are NULL. PostgreSQL supports it, and MySQL has the null-safe equality operator, written as less-than, equals, greater-than, which we negate with NOT.

2Missing and Extra Rows With EXCEPT

Assume email identifies a customer in both tables. The missing and extra checks are two EXCEPT queries.

SQL
-- rows in the old table that did not arrive unchanged
SELECT email, name FROM old_customers
EXCEPT
SELECT email, name FROM customers; -- ('bo@x.com', 'Bo'), ('cy@x.com', 'Cy')
-- rows in the new table that were not in the old one
SELECT email, name FROM customers
EXCEPT
SELECT email, name FROM old_customers; -- ('cy@x.com', 'Cyrus')

Look at the output. 'bo@x.com' is really missing. But 'cy@x.com' appears in both results: once with the old name Cy and once with the new name Cyrus. The reason is that EXCEPT compares whole rows. A row with one changed column is a different row, so it counts as missing from the new side and extra on the new side at the same time. With a few rows we can spot this, with thousands of changes the two lists become hard to read.

3Changed Names by Joining on the Key

When the tables share a key, joining on it gives one clear row per difference. We can produce all three categories in one pass with a FULL OUTER JOIN, which keeps unmatched rows from both sides.

SQL
SELECT COALESCE(o.email, n.email) AS email,
CASE WHEN n.email IS NULL THEN 'missing'
WHEN o.email IS NULL THEN 'extra'
ELSE 'name changed' END AS problem,
o.name AS old_name, n.name AS new_name
FROM old_customers o
FULL OUTER JOIN customers n ON n.email = o.email
WHERE n.email IS NULL
OR o.email IS NULL
OR o.name IS DISTINCT FROM n.name;
-- bo@x.com | missing | Bo | NULL
-- cy@x.com | name changed | Cy | Cyrus
-- di@x.com | name changed | NULL | Di

Notice the last row. The old name was NULL and the new one is Di. With o.name <> n.name that row would have been hidden, because NULL <> 'Di' is unknown and WHERE drops unknown. IS DISTINCT FROM reports it.

One more check belongs here: duplicates. If email is not enforced as unique in the legacy table, the join multiplies rows. Before comparing, we run SELECT email, count(*) FROM old_customers GROUP BY email HAVING count(*) > 1 on both sides, and we also compare plain row counts. It is also worth deciding up front whether emails were normalised during the migration, for example lowercased, because then the join key itself has to apply the same rule.

4Scaling the Comparison to 80 Million Rows

A full outer join of two 80 million row tables is a large hash join or merge join. It may run for many minutes, use a lot of memory and temporary disk, and compete with production traffic. And if anything fails halfway, we learn nothing. A better approach is to compare cheap fingerprints first and look at rows only where fingerprints differ.

We split both tables into the same buckets by key, compute one hash per bucket over its rows in a fixed order, and compare the bucket hashes. With 4,096 buckets, each holds about 20,000 rows. If only three buckets differ, we run the detailed join on 60,000 rows instead of 80 million.

SQL
-- run the same query on both tables, then compare the two result sets
SELECT abs(hashtext(email)) % 4096 AS bucket,
count(*) AS row_count,
md5(string_agg(email || '|' || coalesce(name, '<null>'), ','
ORDER BY email)) AS bucket_hash
FROM old_customers
GROUP BY 1;
-- bucket 17 | 19873 | 9f2c... (same on both sides: skip)
-- bucket 2051 | 20112 | 41ab... (differs: drill into this bucket only)
-- drill-down for one bucket
... FULL OUTER JOIN as above ...
WHERE abs(hashtext(o.email)) % 4096 = 2051 OR abs(hashtext(n.email)) % 4096 = 2051
Step throughComparing large tables by bucket
  1. Hash each key into one of 4096 bucketssame rule on both tables
  2. Per bucket: row count and md5 of sorted rowsabout 20,000 rows each
  3. Bucket hashes equal?
    YesSkip the bucketNoRun the detailed join on it
  4. Classify rowsmissing, extra, name changed
  5. Store resultsmigration_diff table for follow-up

5 steps in order. Play them, or step through them one at a time.

A few details make this reliable. The text we hash must be built the same way on both sides, with a separator and an explicit marker for NULL, otherwise ('ab', 'c') and ('a', 'bc') look the same. hashtext is an internal PostgreSQL function, so if the two tables live in different systems we use a portable bucket rule, such as a range of a numeric id or the first characters of the key. If there is a numeric primary key, ranges of 20,000 ids are simplest and use the index. And we can run the buckets in batches, so the work can pause and resume.

5Running It on a Consistent Snapshot

If writes keep arriving on the new table while we compare, a customer who signs up during the check looks like an extra row, and a name edited by the customer looks like a migration error. We want both tables as of one moment. In PostgreSQL that means running all the queries inside one REPEATABLE READ transaction, which sees a single snapshot, or exporting a snapshot with pg_export_snapshot() so several parallel sessions share it. If the legacy system is still live, the cleanest point is after the final sync, with writes paused or with a known cutoff timestamp applied to both sides.

We also run the comparison on a read replica or a restored backup rather than on the primary. The work is read-only and heavy, and a replica takes that load away from customers. On a replica, long queries can be cancelled when they conflict with replication, so either enable hot_standby_feedback for the duration or keep each bucket query short, which the bucketed design already does.

6Follow-up questions

Why not just compare row counts?

Counts are a useful first check, but they hide errors that cancel out. Losing 50 rows and duplicating 50 others gives the right count and the wrong data. Counts per bucket narrow things down, and hashes per bucket actually prove the content is the same.

Is md5 safe enough for this?

Yes for this purpose. We are detecting accidental differences, not defending against an attacker crafting collisions, and the chance of two different buckets producing the same md5 by accident is negligible. Any fast hash with a wide output works, as long as both sides build the input text identically.

What if the new table stores names transformed, for example trimmed?

Then we compare against the transformed old value, such as trim(o.name), using exactly the rule the migration applied. Otherwise every transformed row shows as changed and the real problems drown in expected noise. The comparison should encode the migration's specification.

7Conclusion

In this answer, we found missing and extra rows with EXCEPT in both directions and saw that a changed row appears in both lists, because EXCEPT compares whole rows. A FULL OUTER JOIN on email with IS DISTINCT FROM gives one clear row per problem and does not miss NULL names. For 80 million rows, we compared counts and md5 hashes per key bucket and drilled into only the buckets that differ, and we ran everything on a replica inside one snapshot so that live writes do not show up as false differences.

What to say in the interviewAbout 90 seconds aloud

Open with

For the basic check I would use EXCEPT in both directions: old_customers EXCEPT customers gives rows that did not arrive unchanged, and the reverse gives extra rows. The catch is that EXCEPT compares whole rows, so a customer whose name changed shows up in both lists, once with each name.

Then, if they want more

Since email is the key, I would rather do a FULL OUTER JOIN on email and classify each row as missing, extra, or name changed, and I would compare names with IS DISTINCT FROM, because a plain not-equals returns unknown when one side is NULL and hides that change.

Before that I check for duplicate emails on both sides, since they would multiply the join. On 80 million rows I would not run one giant join on the primary.

I would split both tables into the same buckets, say 4,096 by a hash of the email or by id ranges, compute a row count and an md5 of the sorted rows per bucket, and compare those small results. Only the buckets that differ get the detailed join.

I would run it on a replica or a restored copy, inside one REPEATABLE READ transaction or an exported snapshot, so that both tables are compared at the same point in time and new signups do not appear as errors. Results go into a diff table so people can work through them.

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.
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 "You migrated customers from a legacy table old_customers(email, name) to...": https://scrivio-interview-library.netlify.app/databases/sql-fundamentals/90f4d701fa/