Skip to main content
Back to Academy🔑 0. Analytics Foundations (Start Here)
5 min read
Try Hands-on Lab
VISUAL LESSON0. Analytics Foundations (Start Here)

Primary Keys vs. Foreign Keys Explained Simply

Understand how Primary Keys uniquely identify every row, how Foreign Keys link tables safely, when to use Surrogate Keys vs. Natural Keys, and how keys prevent orphan records.

Primary Key vs Foreign KeySurrogate Key vs Natural KeyReferential Integrity SQLOne-to-Many Database RelationshipsComposite Primary KeyDatabase Normalization

Explain Like I'm New: Passport Numbers & Flight Boarding Passes

Think of an airport database with two notebooks: - `passengers` notebook: Every traveler gets a unique Passport Number (Primary Key). Two people can share the same name (*"John Smith"*), so names are terrible IDs—passport numbers never collide and are never blank. - `boarding_passes` notebook: Each ticket writes down the traveler's Passport Number (Foreign Key) to point back to the passengers notebook instead of re-typing their birthday, home address, and citizenship on every single flight.

Key Beginner Takeaway: A Primary Key (PK) guarantees each row in a table has a unique, non-null ID badge. A Foreign Key (FK) is a pointer column in another table that references that PK cleanly without copying redundant data everywhere.

Core Terminology & Key Types Compared

Key TypePlain-English RuleCan It Be NULL?Must It Be Unique?Example
Primary Key (PK)Main unique identifier for 1 row in a table.Never (NOT NULL)Yescustomer_id = 4091
Composite Primary KeyTwo or more columns combined form uniqueness.Never in any partCombined tuple is unique(order_id, line_number)
Foreign Key (FK)Column storing the PK of another table to connect them.Sometimes (optional relationship)No (1 customer can place 50 orders!)orders.customer_id -> customers.customer_id
Natural KeyReal-world business code already in use.NoYes (ideally)country_code = 'US', sku_code, email
Surrogate KeyArtificial ID generated solely by the data system.NoAlwaysAUTO INCREMENT int or SHA2 / UUID hash

Why Separating Tables Beats One Giant Spreadsheet

Suppose a beginner stores everything in one wide Excel-style sheet:

order_idcustomer_namecustomer_emailcustomer_cityproductprice
101Maya Raomaya@old.comLondonMouse25.00
102Maya Raomaya@old.comLondonLaptop1200.00
103Maya Raomaya@new.comManchesterStand40.00

Notice the chaos (Update Anomalies): 1. Maya updated her email on Order 103, leaving stale emails on 101 and 102! 2. If you delete Order 101 from a customer who only ordered once, you lose the customer completely (Delete Anomaly)!

Splitting into `dim_customers` (PK: customer_id) and `fact_orders` (PK: order_id, FK: customer_id) stores Maya's current email in one single place!

CREATE TABLE dim_customers (
  customer_id BIGINT PRIMARY KEY,
  full_name   STRING NOT NULL,
  email       STRING NOT NULL,
  city        STRING
);

CREATE TABLE fact_orders (
  order_id    BIGINT PRIMARY KEY,
  customer_id BIGINT NOT NULL REFERENCES dim_customers(customer_id),
  order_date  DATE   NOT NULL,
  total_usd   DECIMAL(18, 2) NOT NULL
);

Surrogate Keys vs. Natural Keys: When to Choose Which

Beginners often ask: "Why don't we just use `email` or `ssn` as the Primary Key?"

Four reasons production Lakehouses generate Surrogate Keys (customer_sk or deterministic hash keys like MD5/SHA2): 1. Natural keys change! Users change emails, company tickers change (FB -> META), SKUs get reassigned. Changing a Primary Key cascades updates across millions of historical fact rows. 2. Privacy compliance (GDPR/PII): Never expose emails or SSNs in foreign keys spread across 50 downstream analytics tables—integer or hashed surrogate keys isolate PII inside one secured dimension table. 3. SCD Type 2 history requires multiple rows per natural ID: If Maya lived in London in 2025 and Manchester in 2026, she appears twice in dim_customers. Only a Surrogate Key (customer_sk = 1001 vs customer_sk = 1002) can tell the two historical snapshots apart! 4. Join speed: Fixed-width integers (BIGINT) join much faster than variable-length 45-character email strings.


Data Engineering Watch-Out: Constraints in Lakehouses

In traditional transactional databases (OLTP like PostgreSQL), PRIMARY KEY and FOREIGN KEY constraints block bad inserts immediately.

In modern cloud data warehouses and Lakehouses (Delta Lake, Snowflake, BigQuery), PK/FK constraints are typically `INFORMATIONAL` (`RELY` / `NORELY`) — meaning they tell the query optimizer and Unity Catalog how tables connect, but the engine does NOT stop duplicate inserts automatically!

That is why Data Engineers MUST run automated Referential Integrity & Uniqueness tests:

-- 1. Check Primary Key Uniqueness (Must return 0 rows!)
SELECT customer_id, COUNT(*) AS dup_count
FROM dim_customers
GROUP BY customer_id
HAVING COUNT(*) > 1;

-- 2. Check for Orphan Foreign Keys (Must return 0 rows!)
SELECT o.order_id, o.customer_id
FROM fact_orders o
LEFT JOIN dim_customers c ON o.customer_id = c.customer_id
WHERE c.customer_id IS NULL;

Common Beginner Mistakes (And How to Fix Them)

  1. Treating names or timestamps as Primary Keys: Two transactions often arrive in the exact same millisecond, and two customers often share a name. Always verify uniqueness across full history.
  2. Storing negative / missing Foreign Keys inconsistently: For unknown dimension lookups during streaming ingestion, map missing FKs to a dedicated `-1` ("Unknown / Late Arriving") surrogate row in the dimension table so INNER JOIN doesn't drop revenue!

Quick Cheat Sheet

  1. Primary Key: Unique, non-null ID for each row in *this* table.
  2. Foreign Key: Pointer referencing the PK of *another* table.
  3. Surrogate Key: Generated ID (1, 2, 3 or hash) needed for PII separation and SCD Type 2 history.
  4. Always test PK uniqueness and FK orphans in Lakehouse pipelines (HAVING COUNT(*) > 1 & LEFT JOIN ... WHERE pk IS NULL).

Comprehension & Architecture Check (3 Questions)

Test your understanding of the concepts covered in this lesson.

1. Which SQL clause filters groups AFTER GROUP BY has counted rows?
2. Can a Foreign Key column appear multiple times in a Fact table?
3. What happens if your dimension table accidentally has two rows with the same Primary Key?
Practice What You Learned

FOUNDATIONS-1: Tables, Rows & Spotting Duplicate Primary Keys

A customer table should have one row per customer_id. Because of an import glitch, some customer_id values appear more than once in bronze.customers_raw. Write a SQL query that finds every duplicate customer_id and shows how many times each one appears.

Solve Challenge