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.
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 Type | Plain-English Rule | Can It Be NULL? | Must It Be Unique? | Example |
|---|---|---|---|---|
| Primary Key (PK) | Main unique identifier for 1 row in a table. | Never (NOT NULL) | Yes | customer_id = 4091 |
| Composite Primary Key | Two or more columns combined form uniqueness. | Never in any part | Combined 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 Key | Real-world business code already in use. | No | Yes (ideally) | country_code = 'US', sku_code, email |
| Surrogate Key | Artificial ID generated solely by the data system. | No | Always | AUTO INCREMENT int or SHA2 / UUID hash |
Suppose a beginner stores everything in one wide Excel-style sheet:
| order_id | customer_name | customer_email | customer_city | product | price |
|---|---|---|---|---|---|
| 101 | Maya Rao | maya@old.com | London | Mouse | 25.00 |
| 102 | Maya Rao | maya@old.com | London | Laptop | 1200.00 |
| 103 | Maya Rao | maya@new.com | Manchester | Stand | 40.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
);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.
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;INNER JOIN doesn't drop revenue!1, 2, 3 or hash) needed for PII separation and SCD Type 2 history.HAVING COUNT(*) > 1 & LEFT JOIN ... WHERE pk IS NULL).Test your understanding of the concepts covered in this lesson.
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.