DWH Interview Question 11 - Primary key, foreign key, natural key, composite key: what is the difference?

Data Warehouse Interview Q&A · Question 11

In this post we are going to cover the four kinds of keys that come up in every database interview: primary key, foreign key, natural key and composite key.

Keys are how a database knows which row is which, and how tables point to each other. A primary key gives each row its identity. A foreign key makes sure a reference points to a row that really exists. A natural key is an identifier from the real world, and a composite key is an identity made from more than one column.

We will build a few small TB Shop tables and then try to break each rule with SQL, so we can see exactly what each key protects.

Question 11 of the Real DWH Question and Answers series on TechBrothersIT.

The interview answer

Say this first

A primary key uniquely identifies each row and can't be NULL. A foreign key references another table's primary key, so relationships stay valid. A natural key comes from the real world, like an email or a product code. A composite key uses two or more columns together. Columns that could each be the primary key are candidate keys; the ones not chosen become alternate (unique) keys.

Candidate and alternate keys are a nice bonus to mention, and we will see both in the demo.

Let's create some sample data

We need four tables: customers, orders with a foreign key to customers, order_items with a composite key, and orders_no_fk, the same orders table without a foreign key so we can see what goes wrong.

Sample data — run this first
DROP TABLE IF EXISTS order_items;
DROP TABLE IF EXISTS orders;
DROP TABLE IF EXISTS orders_no_fk;
DROP TABLE IF EXISTS customers;

CREATE TABLE customers (
  customer_id INT PRIMARY KEY,           -- primary key
  email       VARCHAR(100) NOT NULL UNIQUE, -- natural key, kept unique
  name        VARCHAR(50)
);
CREATE TABLE orders (
  order_id    INT PRIMARY KEY,
  customer_id INT NOT NULL REFERENCES customers(customer_id),  -- foreign key
  order_date  DATE
);
CREATE TABLE order_items (
  order_id   INT REFERENCES orders(order_id),
  product_id INT,
  qty        INT,
  PRIMARY KEY (order_id, product_id)     -- composite key
);
-- the same orders table WITHOUT a foreign key, to see what goes wrong
CREATE TABLE orders_no_fk (
  order_id    INT PRIMARY KEY,
  customer_id INT,
  order_date  DATE
);

INSERT INTO customers VALUES
  (1, 'sara@example.com', 'Sara Khan'),
  (2, 'omar@example.com', 'Omar Ali'),
  (3, 'lina@example.com', 'Lina Park');
INSERT INTO orders VALUES
  (1001, 1, '2026-01-05'), (1002, 2, '2026-01-09'), (1003, 1, '2026-02-02');
INSERT INTO order_items VALUES
  (1001, 101, 1), (1001, 102, 2), (1002, 103, 1), (1003, 101, 1);
INSERT INTO orders_no_fk VALUES
  (1001, 1, '2026-01-05'), (1002, 2, '2026-01-09'), (1003, 99, '2026-02-02');

Let's look at the customers first.

Query
SELECT * FROM customers ORDER BY 1;
Result3 rows · 3 columns
customer_idemailname
1sara@example.comSara Khan
2omar@example.comOmar Ali
3lina@example.comLina Park

customer_id is the primary key. email is also unique, because it is a natural key we protect with a UNIQUE constraint.

Query
SELECT * FROM orders ORDER BY 1;
Result3 rows · 3 columns
order_idcustomer_idorder_date
100112026-01-05
100222026-01-09
100312026-02-02

Each order has its own primary key, order_id, and a customer_id that must exist in customers.

Query
SELECT * FROM order_items ORDER BY 1;
Result4 rows · 3 columns
order_idproduct_idqty
10011011
10011022
10021031
10031011

Here order_id repeats and product_id repeats, but the pair is unique.

Query
SELECT * FROM orders_no_fk ORDER BY 1;
Result3 rows · 3 columns
order_idcustomer_idorder_date
100112026-01-05
100222026-01-09
1003992026-02-02

This copy has no foreign key, and order 1003 points to customer 99, who does not exist.

Step 1: Primary key - one row, one identity

Let's start with the primary key. A table can have only one, its values must be unique, and they can never be NULL. Now let's try to add a second customer with ID 1.

Statement
INSERT INTO customers
VALUES (1, 'new@example.com', 'New Person');
Error (expected) — PostgreSQL
duplicate key value violates unique constraint "customers_pkey"
DETAIL:  Key (customer_id)=(1) already exists.

Rejected with a duplicate key error on customers_pkey: customer_id 1 already exists. Because the database will not let two rows share an identity, every other table can point to customer 1 and mean exactly one person.

Step 2: Natural key - candidate and alternate keys

Email also identifies a customer uniquely, and it comes from the real world, so it is a natural key. customer_id and email are both candidate keys: either one could be the primary key. We chose customer_id, so email becomes an alternate key, and we still protect it with a unique constraint. Let's try to register Sara's email a second time with a new ID.

Statement
INSERT INTO customers
VALUES (4, 'sara@example.com', 'Sara Copy');
Error (expected) — PostgreSQL
duplicate key value violates unique constraint "customers_email_key"
DETAIL:  Key (email)=(sara@example.com) already exists.

Rejected again, this time by customers_email_key, even though customer_id 4 is new. Why not just use email as the primary key? Because people change their email. Primary keys should be stable, since other tables point to them.

Step 3: Foreign key - an order for a customer that does not exist

orders.customer_id is a foreign key that references customers.customer_id. The rule is simple: every customer ID in orders must exist in customers. Let's try to insert an order for customer 99.

Statement
INSERT INTO orders
VALUES (1004, 99, '2026-03-01');
Error (expected) — PostgreSQL
insert or update on table "orders" violates foreign key constraint "orders_customer_id_fkey"
DETAIL:  Key (customer_id)=(99) is not present in table "customers".

Rejected by orders_customer_id_fkey: key 99 is not present in table customers. The relationship stays valid.

Step 4: Without a foreign key, orphans slip in

Now the same orders without a foreign key. Nothing stopped order 1003 from pointing to customer 99. Let's find it with the classic orphan query: a LEFT JOIN to customers, keeping only rows where no customer matched.

Query
SELECT o.order_id, o.customer_id
FROM orders_no_fk o
LEFT JOIN customers c
  ON c.customer_id = o.customer_id
WHERE c.customer_id IS NULL;
Result1 row · 2 columns
order_idcustomer_id
100399

One orphan: order 1003 with customer_id 99. Any report that joins orders to customers will silently drop it. Remember this left join pattern, because interviewers love asking how you would detect orphan rows.

Step 5: Composite key - two columns, one identity

In order_items, neither column is unique on its own: one order has many products, and one product appears in many orders. But the pair (order_id, product_id) is unique, so the primary key is both columns together. Let's try to add product 101 to order 1001 a second time.

Statement
INSERT INTO order_items
VALUES (1001, 101, 5);
Error (expected) — PostgreSQL
duplicate key value violates unique constraint "order_items_pkey"
DETAIL:  Key (order_id, product_id)=(1001, 101) already exists.

Rejected by order_items_pkey: the pair (1001, 101) already exists. The correct move is to update the quantity on the existing line instead of adding a new one.

Follow-up questions interviewers ask

Can a foreign key be NULL?

Yes, when the relationship is optional.

Can a table have several foreign keys?

Yes, one per relationship (customer, store, sales rep...).

Do cloud warehouses enforce foreign keys?

Usually not; Snowflake and BigQuery treat them as informational, so pipelines must check for orphans.

The full script

Here is everything from this post in one script. Copy it and run it top to bottom.

Full script — copy and run top to bottom
-- ========================================================================
-- Data Warehouse Interview Q&A #11 - Primary, foreign, natural and composite keys
-- TechBrothersIT. Sample data is invented for teaching.
-- Standard SQL, tested on PostgreSQL 16. Runs top to bottom in one go.
-- Run it in an empty database or schema: other videos reuse table names
-- like dim_customer, and their leftover tables can block the DROPs below.
-- PostgreSQL example:  CREATE SCHEMA dwh_q11;  SET search_path TO dwh_q11;
-- ========================================================================

-- Step 0: create and load the sample data
DROP TABLE IF EXISTS order_items;
DROP TABLE IF EXISTS orders;
DROP TABLE IF EXISTS orders_no_fk;
DROP TABLE IF EXISTS customers;

CREATE TABLE customers (
  customer_id INT PRIMARY KEY,           -- primary key
  email       VARCHAR(100) NOT NULL UNIQUE, -- natural key, kept unique
  name        VARCHAR(50)
);
CREATE TABLE orders (
  order_id    INT PRIMARY KEY,
  customer_id INT NOT NULL REFERENCES customers(customer_id),  -- foreign key
  order_date  DATE
);
CREATE TABLE order_items (
  order_id   INT REFERENCES orders(order_id),
  product_id INT,
  qty        INT,
  PRIMARY KEY (order_id, product_id)     -- composite key
);
-- the same orders table WITHOUT a foreign key, to see what goes wrong
CREATE TABLE orders_no_fk (
  order_id    INT PRIMARY KEY,
  customer_id INT,
  order_date  DATE
);

INSERT INTO customers VALUES
  (1, 'sara@example.com', 'Sara Khan'),
  (2, 'omar@example.com', 'Omar Ali'),
  (3, 'lina@example.com', 'Lina Park');
INSERT INTO orders VALUES
  (1001, 1, '2026-01-05'), (1002, 2, '2026-01-09'), (1003, 1, '2026-02-02');
INSERT INTO order_items VALUES
  (1001, 101, 1), (1001, 102, 2), (1002, 103, 1), (1003, 101, 1);
INSERT INTO orders_no_fk VALUES
  (1001, 1, '2026-01-05'), (1002, 2, '2026-01-09'), (1003, 99, '2026-02-02');


-- Step 1: Primary key: a second customer with id 1 is rejected
-- This statement is EXPECTED TO FAIL: it shows the constraint protecting the data.
-- Remove the leading -- to run it and see the error.
-- INSERT INTO customers
-- VALUES (1, 'new@example.com', 'New Person');

-- Step 2: Unique natural key: a second customer with the same email is rejected
-- This statement is EXPECTED TO FAIL: it shows the constraint protecting the data.
-- Remove the leading -- to run it and see the error.
-- INSERT INTO customers
-- VALUES (4, 'sara@example.com', 'Sara Copy');

-- Step 3: Foreign key: an order for a customer that does not exist is rejected
-- This statement is EXPECTED TO FAIL: it shows the constraint protecting the data.
-- Remove the leading -- to run it and see the error.
-- INSERT INTO orders
-- VALUES (1004, 99, '2026-03-01');

-- Step 4: Without a foreign key, orphan rows slip in
SELECT o.order_id, o.customer_id
FROM orders_no_fk o
LEFT JOIN customers c
  ON c.customer_id = o.customer_id
WHERE c.customer_id IS NULL;

-- Step 5: Composite key: the same product twice in one order is rejected
-- This statement is EXPECTED TO FAIL: it shows the constraint protecting the data.
-- Remove the leading -- to run it and see the error.
-- INSERT INTO order_items
-- VALUES (1001, 101, 5);

Key points

  • Primary key: unique, not NULL, one per table
  • Natural key: from the real world; candidates not chosen become alternate (unique) keys
  • Foreign key: every reference must exist; find orphans with a LEFT JOIN
  • Composite key: two or more columns, unique as a combination
  • Warehouses often don't enforce FKs: pipelines must check
Next in this series

Question 12 — What is denormalization? What is denormalization, and when should you use it?

Every query and every result on this page was run on PostgreSQL 16 using the script above. The SQL is standard and runs on most databases with small changes (noted in the script). All tables and data are invented demo data for teaching.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.