Aller au contenu

Leçon 22 · Cleaning in SQL and Spreadsheets

Deduplicating and Validating in SQL

Remove duplicates in SQL with ROW_NUMBER, write validation queries that return only failures, and block new bad rows with CHECK, UNIQUE and key constraints.

SQL is very good at two jobs: choosing one row from each group of duplicates, and listing rows that break rules. This lesson builds both, then uses constraints so that the database rejects many kinds of new bad data.

Find duplicate groups

Group by the key and keep the groups with more than one row.

SQL Find repeated keys and conflicts

Press Run (or Ctrl + Enter) to see the result here.

A distinct_cities value above 1 signals a conflict. Remember that COUNT(DISTINCT ...) ignores NULL.

Keep one row with ROW_NUMBER

The window function ROW_NUMBER numbers the rows within each group in the order you choose. Keeping number 1 gives one row per key.

SQL Keep the newest row per email

Press Run (or Ctrl + Enter) to see the result here.

The ORDER BY inside OVER is your survivorship rule: newest first, then a source priority, then a final tie-breaker. If two rows tie on everything in that list but differ in another column, the database may pick either one, so make the ordering complete. To review what you would remove, select rn > 1 instead.

SELECT DISTINCT removes only rows that are identical in all selected columns. It cannot choose between versions.

Write checks that return failures

A useful validation query returns only bad rows, with a rule name. An empty result means those rules passed. Combine rules with UNION ALL.

SQL One report for many rules

Press Run (or Ctrl + Enter) to see the result here.

Watch for NULL in rules. If qty is NULL, then qty <= 0 is unknown, so the row would not be returned without the IS NULL test. The date rule skips unshipped orders, because comparing with NULL is unknown. Here that is intended. The comparison also works only because the dates are consistent ISO text.

Block bad rows with constraints

Constraints reject bad data when it is written.

SQL Constraints reject bad rows

Press Run (or Ctrl + Enter) to see the result here.

INSERT OR IGNORE is SQLite syntax that skips rows that violate these constraints, so you can see which one survives. In real loads, do not ignore violations silently. Without that clause the statement fails, which is usually what you want. Load into a staging table first, route bad rows to quarantine, then insert the good ones.

Existing data must satisfy a constraint before many databases let you add it. Syntax and support for adding constraints later differ between databases. SQLite also has flexible column types, so a declared type alone does not reject every wrong value.

Counting checks

Compare staging and clean tables: row counts, distinct keys and sums. Clean rows plus rejected rows plus removed duplicates should equal the raw count, when each raw row lands in exactly one of those groups.

Common mistake: using NOT IN with a subquery that can return NULL. The condition is then never true, so you may get no rows at all. NOT EXISTS, as used above, avoids that trap.

Review before you remove

Treat a deduplication query as a proposal first. Select the rows that would be removed, along with the row that would survive, and read a sample of those pairs. Look especially at groups that are unusually large. A group with hundreds of rows often means that the key is a placeholder, such as an empty email or [email protected], shared by many unrelated records.

That case is worth handling in the query itself. Exclude missing and placeholder keys from deduplication, and route them to review. Otherwise PARTITION BY puts every NULL key into one partition, and keeping row number 1 would throw away all the others.

Make the checks run automatically

Store each validation query with a name, a severity and an owner. A script or scheduled job can run them after each load and fail the job if a stopping rule returns rows. Save the counts, not only the latest result, so you can see whether a problem is growing.

Keep queries readable. Several short checks with clear names are easier to maintain than one huge query that tries to test everything at once. On large tables, you may check only newly loaded rows for row-level rules, but uniqueness must still be compared against the existing data.

Count before and after

Wrap every deduplication in three numbers: rows going in, distinct keys and rows coming out. When every row has a usable key and you keep one row per key, the last two numbers must be equal. If rows without a key go to review, count them separately and check that all three groups add up.

Also compare an important sum before and after. A large drop in revenue after removing "duplicates" is a reason to stop and look. It may be correct, after a true double load, or it may show that your key is missing a column and that you are discarding real events.

Portability

The ideas travel well, but details differ. Some databases need an alias for a subquery, some have different date and pattern functions and some offer extra clauses that filter window function results directly. Test every query on the system you will actually use, with a few rows that must fail.

Keep the evidence

Save the removed rows in their own table with the run date and the rule that removed them. If someone questions a total later, you can show exactly which version survived and why. It also lets you restore rows when a key turns out to be wrong. Protect that table like the original, since it contains the same kinds of personal data, and delete it according to your retention rules.

Check your understanding

Quick check · 3 questions

of 3 answered You scored / 3 · perfect!

  1. 1. What does the ORDER BY inside ROW_NUMBER's OVER clause decide?

    It expresses the survivorship rule for choosing which duplicate to keep.
  2. 2. Why is a complete tie-breaker needed?

    Without it, the database may number either tied row first.
  3. 3. What should a failure-listing validation query return when data passes?

    Returning only failures makes success easy to check automatically.

Summary

  • Group by normalized keys to find duplicates.
  • Use ROW_NUMBER with a complete ordering to keep one row.
  • Write checks that return only failures, and mind NULL.
  • Add constraints to stop bad rows at the database.

Next: Cleaning Data in Spreadsheets

Votre progression est enregistrée dans ce navigateur. Aucun compte nécessaire.