smartyfy.mrindigi.com

Databases & SQL Master Course — 073. Natural and Surrogate Keys

Lesson 073 Natural and Surrogate Keys

Prerequisites and objectives

You understand candidate keys, composite identity, and table grain. You will compare natural and surrogate identifiers using stability, scope, and meaning; preserve business uniqueness when choosing a surrogate; and test a code change without confusing a product’s identity with its current external label.

Create the practice fixture

Use a fresh disposable SQLite database with foreign keys enabled. Two suppliers both use code A1 for different catalog items. The natural business identifier is therefore supplier plus supplier code. The internal item_id is a surrogate assigned by the database model. All write experiments are rolled back.

PRAGMA foreign_keys=ON;
CREATE TABLE suppliers (supplier_id INTEGER PRIMARY KEY, name TEXT NOT NULL);
CREATE TABLE catalog_items (
 item_id INTEGER PRIMARY KEY,
 supplier_id INTEGER NOT NULL REFERENCES suppliers(supplier_id),
 supplier_code TEXT NOT NULL,
 title TEXT NOT NULL,
 UNIQUE(supplier_id,supplier_code)
);
CREATE TABLE requested_items (
 request_id INTEGER PRIMARY KEY,
 item_id INTEGER NOT NULL REFERENCES catalog_items(item_id)
);
INSERT INTO suppliers VALUES (1,'North Supply'),(2,'South Supply');
INSERT INTO catalog_items VALUES (10,1,'A1','Notebook'),(11,2,'A1','Notebook');
INSERT INTO requested_items VALUES (101,10);

Compare the roles of the two identifiers

A natural key comes from the domain, such as a supplier’s catalog code within that supplier’s scope. A surrogate key is introduced to identify a row without encoding those business attributes. Neither category is automatically superior. The right choice depends on what can change, where identifiers are used, and what uniqueness the domain actually guarantees.

Our item_id gives internal request rows a compact, stable reference. The supplier/code pair remains a required unique business identifier for imports and lookup. Removing that alternate constraint would allow two internal rows for the same supplier catalog item, even though each had a perfectly unique surrogate identifier.

SELECT item_id,supplier_id,supplier_code,title FROM catalog_items ORDER BY item_id;
SELECT r.request_id,c.item_id,s.name,c.supplier_code FROM requested_items AS r JOIN catalog_items AS c ON c.item_id=r.item_id JOIN suppliers AS s ON s.supplier_id=c.supplier_id;

Both catalog rows are valid because their suppliers differ. A lookup using only A1 would be ambiguous. The request points specifically to item ten, which currently corresponds to North Supply’s A1. The title Notebook is descriptive and deliberately not unique.

Test stability rather than assuming it

Suppose North Supply renames its code from A1 to N-100 while the catalog item remains the same business object. Updating the alternate code can leave the internal item_id unchanged, so existing request references still identify the same item. This is one reason a surrogate can simplify internal relationships.

However, keeping an identifier unchanged is correct only if identity truly persists. If a supplier reuses A1 for a different product, the old and new products may require separate identities and historical code mappings. A surrogate does not decide this semantic question; it merely provides a place to express the chosen answer.

Request 101 retains its item_id 10 reference while item 10’s supplier 1 code changes from A1 to N-100. Item 11 belongs to supplier 2 and retains its valid A1 code. Complete alternate business keys (1, N-100) and (2, A1) remain distinct, protected by a composite UNIQUE constraint.
An internal reference can survive a code rename when the underlying object remains the same. Code scope and historical meaning still require explicit policies. Open full-size diagram

Evaluate costs and boundaries

A natural key can make data understandable without an extra lookup, especially when it is short, stable, and governed by a trustworthy standard. A long composite natural key can make references wider and code changes more expensive. A surrogate simplifies some references but adds a mapping that imports, exports, and reconciliation must preserve.

Do not use a generated integer as proof of global identity across separate databases. Item ten in one database may be unrelated to item ten elsewhere. Integrations need an explicitly scoped identifier or a mapping process. Similarly, an unpredictable identifier is not an authorization system; access checks must still control who can read or modify a row.

Preserve history when codes change

A current catalog table stores the current supplier code. If reports must reproduce the code printed on an old request, that historical fact may need a snapshot or a validity-dated mapping. Joining an old request to today’s code answers a different question: what is the item’s current code?

Write the identity policy before implementing updates. Which changes preserve the same item? Which create a new item? Can external codes be reused? Are codes unique globally or only per supplier? These decisions shape keys, alternate constraints, and historical tables more than a preference for integers versus text.

Four worked exercises

Exercise 1

Rename North Supply’s code while keeping the internal item identity.

Worked solution
BEGIN;
UPDATE catalog_items SET supplier_code='N-100' WHERE item_id=10;
SELECT r.request_id,c.item_id,c.supplier_code FROM requested_items AS r JOIN catalog_items AS c ON c.item_id=r.item_id;
ROLLBACK;

The request still references item ten and now displays its current code N-100. This shows stable internal reference behavior. It also demonstrates why a current join cannot recover the code that was printed historically unless that information is stored separately.

Exercise 2

Try creating a second internal row for North Supply’s existing A1.

Worked solution
BEGIN;
INSERT INTO catalog_items VALUES (12,1,'A1','Another title');
SELECT COUNT(*) FROM catalog_items;
ROLLBACK;

The alternate composite constraint rejects the duplicate business identity. A new surrogate value is not enough to make the row legitimate. Keep business-key enforcement even when most foreign keys use the surrogate.

Exercise 3

Find the ambiguity caused by looking up supplier code without its scope.

Worked solution
SELECT item_id,supplier_id FROM catalog_items WHERE supplier_code='A1' ORDER BY item_id;

Two rows match because A1 is scoped to its supplier. A correct integration lookup includes the supplier identifier or another unambiguous namespace. Choosing the first row would silently select an arbitrary business object.

Exercise 4

Add another differently coded Notebook from North Supply.

Worked solution
BEGIN;
INSERT INTO catalog_items VALUES (12,1,'A2','Notebook');
SELECT item_id,supplier_code FROM catalog_items WHERE supplier_id=1 ORDER BY item_id;
ROLLBACK;

The shared title is allowed because it is descriptive, not an identifier. A title-based deduplication rule would collapse distinct supplier catalog items. Similar-looking descriptions need domain review rather than automatic identity assumptions.

Knowledge check

Question 1

What is the natural key in this fixture?

  1. Supplier code alone
  2. Supplier identifier plus supplier code
  3. Item title alone
  4. The request identifier
Answer and explanation

B. The code is unique only within its supplier namespace.

Question 2

What must remain when a surrogate becomes the primary key?

  1. Any required business-key uniqueness constraints
  2. Every business field must become nullable
  3. All natural identifiers must be deleted
  4. Only a row-count check
Answer and explanation

A. Surrogate uniqueness does not prevent duplicate business entities by itself.

Question 3

What does changing A1 to N-100 demonstrate?

  1. Every code change always means the same product
  2. Historical printed codes are automatically preserved
  3. Foreign keys become unnecessary
  4. A stable internal reference can survive a business-code change
Answer and explanation

D. The tested mapping keeps item identity stable, but history and identity policy remain separate concerns.

Question 4

Why is item_id ten not automatically globally meaningful?

  1. The internal ID takes its identity scope from the supplier code
  2. The PRIMARY KEY declaration makes values unique across databases
  3. Separate databases can assign ten to different objects
  4. Exporting the row automatically assigns a globally unique identity
Answer and explanation

C. Identifier scope must be explicit across systems.

Question 5

Does an unguessable identifier replace access control?

  1. Yes, if the identifier is long enough
  2. No, authorization still governs row access
  3. Yes, whenever a foreign key exists
  4. Only for rows with natural keys
Answer and explanation

B. Identity and permission are different responsibilities.

Pitfalls and summary

Do not treat natural versus surrogate as a contest with one universal winner. Evaluate stability, scope, reuse, reference cost, and historical meaning. Preserve alternate business constraints, and distinguish current codes from past observations. A key choice is successful when it supports the domain’s identity policy consistently.

SQLite behavior and references

Examples were checked with SQLite 3.53.1 on 10 October 2026. Use a SQLite SQL editor; Python is not a prerequisite. Verify dialect-specific functions, comparison rules, and numeric behavior before moving the examples to another engine.

Primary references