Sub topic 3
Keeping Your Own Primary Key Next to the External ID
This chapter assumes you can write basic SQL (INSERT, SELECT, foreign keys) and know what a primary key and a unique constraint are. The examples use PostgreSQL. The previous chapter introduced external IDs, the identifiers another system assigns to its records. Here you decide where that identifier lives in your own schema.
Two identifiers, two jobs
A record that arrives from another system has two identities in your database.
- The internal key is the primary key your database generates. Your tables, foreign keys, and application code use it to refer to the row.
- The external ID is the value the source system uses for the same record. It exists so that a later load can find the row again.
These identifiers do different jobs, so store them in separate columns. The internal key says "which row is this in my database". The external ID says "which record in the other system does this row mirror".
The table design
This is the table from the chapter's running example:
CREATE TABLE customers (
id bigserial PRIMARY KEY,
source_system text NOT NULL,
external_id text NOT NULL,
name text NOT NULL,
email text,
UNIQUE (source_system, external_id)
);The table has three parts that matter here.
idis the primary key. PostgreSQL generates it, and nothing outside your database controls it.external_idholds the source's identifier as plain text.source_systemrecords which system issued that identifier. TheUNIQUEconstraint covers both columns together.
The unique constraint is what makes the external ID usable for matching. The next chapter covers it in detail. For now, note that it creates the index an upsert will rely on.
Why not use the external ID as the primary key
Using the external ID as the primary key looks simpler, because you would have one column and no mapping. It tends to cause problems later.
- You do not control the format. A source can change
C-1001toCUST-1001, switch from strings to numbers, or reuse an identifier after deleting a record. If that value is your primary key, the change spreads into every table that references it. - Two sources can collide. A CRM and a billing system might both have a customer
1001. A bare external ID cannot tell them apart. A composite key of source and ID can, but it makes every foreign key two columns wide. - Foreign keys get larger. A
bigintinternal key is eight bytes. A text external ID is often longer, and it is copied into every child row and every index on those rows. - Not every row has an external ID. Records created inside your own application have no source identifier. They still need a primary key.
- Records get merged. If two source records turn out to describe one customer, you may want one row that is known by two external IDs. That is only possible when the external ID is not the row's identity.
With a separate internal key, the external ID is just an attribute used for matching. If the source changes it, you update one column on one row, and no foreign key is affected.
Foreign keys point at the internal key
Child tables should reference customers.id, not the external ID:
CREATE TABLE orders (
id bigserial PRIMARY KEY,
customer_id bigint NOT NULL REFERENCES customers (id),
total_cents integer NOT NULL
);The relationships look like this:
An order feed from the same source will usually identify its customer by external ID, because that is all the source knows. Your loader has to translate the external ID into the internal key before it writes the order:
INSERT INTO orders (customer_id, total_cents)
SELECT id, 4200
FROM customers
WHERE source_system = 'crm'
AND external_id = 'C-1001';The translation happens once, at the boundary of your system. Everything after it uses customer_id.
Getting the internal key back from an upsert
When you upsert a customer, you often need the internal key straight away, for example to insert that customer's orders. RETURNING provides it:
INSERT INTO customers (source_system, external_id, name, email)
VALUES ('crm', 'C-1001', 'Ada Lovelace', '[email protected]')
ON CONFLICT (source_system, external_id)
DO UPDATE SET name = EXCLUDED.name, email = EXCLUDED.email
RETURNING id;The first time this runs, it inserts a row and returns the new id. On every later run, the conflict sends it to DO UPDATE, and it returns the same id as before. The caller does not need to know which case occurred.
DO UPDATE is what makes RETURNING reliable here. With ON CONFLICT DO NOTHING, a conflicting row is skipped and RETURNING produces no row for it. If you need the key for rows that already exist, use DO UPDATE, or run a follow-up SELECT.
The same applies when a WHERE clause on DO UPDATE skips a row, as in the stale-data guard covered later in this tutorial. A skipped row returns nothing, so a loader that depends on RETURNING must handle an empty result.
Why the internal key never leaves your system
Treat the internal key as private to your database and your application. Two practical rules follow.
- Do not send your
idto the source system as if it were theirs. If a source needs to know about your record, store its identifier on your side, or use a separate column for a reference you both agree on. - Do not rebuild the table by reloading and expect the same ids. Sequence-generated keys depend on insert order. After a reload from scratch, customer
C-1001may get a differentid. Anything that stored the oldidoutside the database, such as a cached URL or an exported spreadsheet, will point at the wrong row. Keep the external ID as the stable handle for cross-system references.
What happens when the external ID changes
Sources sometimes re-key records, for example after a migration. Because the internal key is separate, this is a one-row fix:
UPDATE customers
SET external_id = 'C-2001'
WHERE source_system = 'crm'
AND external_id = 'C-1001';The row keeps its id, so every order still points at the right customer. If you had used the external ID as the primary key, you would have to update the parent row and every child row in the same transaction.
If the source starts sending C-2001 before you run this update, the upsert sees no match and inserts a second row for the same person. You then have a duplicate to merge. Re-keying has to be coordinated with the source, and the mapping from old to new identifiers should be applied before the first load that uses the new ones.
Common errors
| Mistake | Symptom | Fix |
|---|---|---|
| Using the external ID as the primary key | Foreign keys break or need cascading updates when the source changes the ID | Add a generated `id` and keep the external ID as a separate unique column |
| Unique constraint on `external_id` alone | Two source systems with the same ID collide, and one load overwrites the other | Make the constraint `(source_system, external_id)` |
| No unique constraint on the external ID | `ON CONFLICT` fails with an error, or duplicates accumulate | Add the constraint before writing the upsert |
| Storing the internal `id` in the other system | References break after a rebuild | Store and exchange the external ID instead |
| Ignoring a zero row count on the child load | Child records vanish without an error | Check affected rows, or load parents first and fail on a miss |
| Choosing a numeric type for IDs that look numeric | Leading zeros are lost, and long values may overflow | Store as `text` unless the source guarantees a stable integer |
Checklist for a new table
- Give the table a generated primary key.
- Add
external_idandsource_system, bothNOT NULL. - Add a unique constraint over the pair.
- Point foreign keys in other tables at the internal key.
- In loaders, translate external IDs to internal keys at the edge, and check row counts.
Exercise
A teammate proposes dropping the id column from customers and making external_id the primary key, to save a column. Give two concrete problems this causes in this design.
Show answer
Any two of these. (1) The CRM and a second source system can issue the same external ID, so the key collides unless it is widened to include source_system, which makes every foreign key two columns. (2) If the source renames or re-keys a record, the primary key changes, and every orders.customer_id row that references it must change in the same transaction, instead of updating one external_id column. (3) Records created inside your own application have no external ID, so they have no valid primary key. (4) Each child row and index carries a longer text key instead of an eight-byte bigint.