Saltar al contenido

Lección 11 · Duplicates and Identifiers

Keys and Identifiers

Clean identifiers and keys: keep them as text, fix padding carefully, validate check digits, find orphan records and avoid joins that silently multiply rows.

Identifiers connect your data. A key says which record a row is, or which record it refers to. When keys are damaged, joins can fail silently: rows disappear, or they multiply. This lesson shows how to protect and check them.

Kinds of keys

Term Meaning
Primary key Uniquely identifies each row in a table
Foreign key Refers to a row in another table
Composite key Several columns that together are unique
Natural key Comes from the real world, such as a product code
Surrogate key A made-up ID assigned by a system

Natural keys can change or be reused. An email address is a poor permanent key, because people change it and some share it.

Identifiers are text

You never add two postal codes. Store identifiers as text, or you risk losing leading zeros, changing long numbers or showing them in scientific notation. For example, Excel keeps about 15 significant digits for numbers, so a 16-digit code stored as a number gets altered.

Python Normalize IDs with explicit rules

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

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Padding is safe here only because we assume the rule "C plus five digits". Without a documented rule, 42 and 00042 could be different codes. Values such as 42.0 or 4.2E+1 suggest that a tool treated the ID as a number. We reject them for review instead of guessing.

Check digits

Many number schemes include a check digit, computed from the other digits, that catches many typing mistakes. A well-known method is the Luhn algorithm, used by payment card numbers among others. A passing check means the number is well formed, not that it exists or belongs to anyone.

Python Validate a Luhn check digit

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

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Never put real card or government ID numbers in practice data. When you must work with them, follow your organization's security rules.

Referential integrity

A filled foreign key should point to an existing row. A row that points nowhere is an orphan. Check both directions: orders without customers (usually an error) and customers without orders (often normal).

SQL SQL: find orphans and duplicate keys

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

The first result lists two rows for different reasons. C9 refers to a missing customer: a true orphan. O4 has no reference at all. Treat them separately.

Joins that multiply rows

The customer table has two rows for C2. Joining it to orders repeats every C2 order, and sums grow.

SQL SQL: a duplicate key inflates a total

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

Before a join, confirm the key is unique on the side that should have one row. After it, compare row counts and totals. In pandas, merge accepts a validate argument such as "many_to_one" that raises an error when the keys break that expectation. See merging and joining.

Keys that look equal but differ

Hidden causes of failed matches include trailing spaces, different case, different Unicode characters that look alike, mixed types (number versus text) and different padding. When two keys look identical but do not join, print them with repr() in Python and check their lengths.

Mapping tables

When systems use different IDs for the same thing, keep a crosswalk table with columns such as source, source_id and master_id. It documents the links, can be reviewed and survives rebuilds.

Common mistake: using row numbers as IDs. Sorting or reloading changes them, so references end up pointing at the wrong records.

A key checklist

Run these checks on every key before you join or load:

  1. Present: are any key values empty?
  2. Unique: on the side that should have one row per key, does any key repeat?
  3. Format: do all values match the documented shape and length?
  4. Type: is the key text on both sides, with the same padding and case rules?
  5. Coverage: what share of references find a match, and which ones do not?
  6. Stability: did any ID change its meaning since the last delivery?

Check number five deserves attention. A match rate that suddenly falls from nearly everything to much less often points to a format change on one side, such as a new prefix or lost zeros.

Be careful when you combine data from two systems that both number customers from 1. The same number refers to different people. Keep the source name together with the ID until a crosswalk links them to one master ID.

IDs can be personal data even when they look like random codes, because they link records to a person. Replacing a name with an ID does not by itself make a dataset anonymous, so keep protecting it.

When a key must change

Sometimes you have to replace an ID, for example when two customer records are merged. Update every table that refers to it in one controlled step, and keep the old ID in the crosswalk. Old reports, support tickets and files from partners may still use it for a long time.

Never give a retired ID to a new record. Reuse makes old references point at the wrong thing, and that error is very hard to detect because every join still succeeds.

Document each key

For every table, write one line that states its key, its format and the tables that refer to it. This short note helps the next person join the data correctly and notice when a new delivery breaks the promise.

Check your understanding

Quick check · 3 questions

of 3 answered You scored / 3 · perfect!

  1. 1. A value passes a check digit test. What do you know?

    A check digit tests internal consistency only.
  2. 2. What happens when you join to a table with a repeated key?

    Each matching pair produces a row, so one order can appear twice.
  3. 3. What is an orphan record?

    Its foreign key has no matching row.

Summary

  • Keep identifiers as text and pad only by a documented rule.
  • Check digits catch typos but do not prove existence.
  • Look for orphans and check key uniqueness before joins.
  • Keep crosswalk tables instead of overwriting IDs.

Next: Converting Data Types Safely

Tu progreso se guarda en este navegador. No necesitas una cuenta.