SQL primary keys and foreign keys: linking tables safely
A primary key gives every row a unique ID, and a foreign key points to that ID from another table. Together they make sure every order belongs to a customer who actually exists, and they are what every JOIN relies on.
In short: customer_id INTEGER PRIMARY KEY makes customer_id the primary key, unique and never empty. customer_id INTEGER REFERENCES customers(customer_id) in another table is a foreign key: only IDs that exist in customers are allowed there. A key made of several columns goes at the end: PRIMARY KEY (order_id, product_id).
What you should know first: CREATE TABLE and combining tables with JOIN.
Try it now
Sometimes it takes two columns together to make a row unique. A customer buys many products and a product has many buyers, but each pair should only be stored once.
Task To speed up repeat orders, the shop wants to record which products each customer has bought before, with each pair only once. Create the table regular_items with the columns customer_id and product_id (both whole numbers, required). The primary key is made of both columns together. To check it, the exercise adds every pair from the orders (skipping duplicates with INSERT OR IGNORE) and tries a pair with no customer.
orders 18 rows, 5 columns
| order_id | customer_id | order_date | status | employee_id |
|---|---|---|---|---|
| 1001 | 1 | 2026-01-08 | delivered | 3 |
| 1002 | 4 | 2026-01-12 | delivered | 4 |
| 1003 | 3 | 2026-01-20 | delivered | 3 |
| 1004 | 7 | 2026-02-03 | delivered | 4 |
| 1005 | 2 | 2026-02-11 | cancelled | 8 |
| 1006 | 1 | 2026-02-25 | delivered | 3 |
| 1007 | 10 | 2026-03-04 | delivered | 2 |
| 1008 | 5 | 2026-03-17 | delivered | 4 |
| 1009 | 8 | 2026-03-30 | delivered | 3 |
| 1010 | 6 | 2026-04-07 | delivered | 8 |
| 1011 | 12 | 2026-04-22 | delivered | 4 |
| 1012 | 3 | 2026-05-06 | delivered | 3 |
| 1013 | 9 | 2026-05-19 | cancelled | 8 |
| 1014 | 7 | 2026-06-02 | shipped | 4 |
| 1015 | 1 | 2026-06-10 | shipped | 3 |
| 1016 | 11 | 2026-06-12 | open | NULL |
| 1017 | 4 | 2026-06-13 | open | NULL |
| 1018 | 10 | 2026-06-14 | open | NULL |
order_items 38 rows, 4 columns
| order_id | product_id | quantity | unit_price |
|---|---|---|---|
| 1001 | 1 | 40 | 4.79 |
| 1001 | 3 | 25 | 2.79 |
| 1001 | 6 | 4 | 24.9 |
| 1002 | 2 | 2 | 3.49 |
| 1002 | 10 | 3 | 5.49 |
| 1003 | 1 | 60 | 4.69 |
| 1003 | 11 | 6 | 84.9 |
| 1003 | 3 | 50 | 2.59 |
| 1004 | 4 | 3 | 179 |
| 1004 | 9 | 3 | 269 |
| 1005 | 5 | 1 | 449 |
| 1006 | 1 | 30 | 4.79 |
| 1006 | 7 | 10 | 6.99 |
| 1007 | 8 | 2 | 219 |
| 1007 | 11 | 4 | 89.9 |
| 1007 | 1 | 20 | 4.99 |
| 1008 | 4 | 6 | 175 |
| 1008 | 2 | 5 | 3.49 |
| 1009 | 10 | 120 | 4.99 |
| 1009 | 2 | 40 | 3.19 |
| 1009 | 9 | 2 | 279 |
| 1010 | 7 | 2 | 6.99 |
| 1010 | 2 | 1 | 3.49 |
| 1011 | 12 | 1 | 129 |
| 1011 | 1 | 10 | 4.99 |
| 1011 | 3 | 12 | 2.79 |
| 1012 | 6 | 8 | 23.9 |
| 1012 | 1 | 40 | 4.69 |
| 1013 | 9 | 1 | 279 |
| 1014 | 5 | 2 | 439 |
| 1014 | 4 | 2 | 179 |
| 1015 | 1 | 50 | 4.79 |
| 1015 | 11 | 2 | 89.9 |
| 1016 | 10 | 4 | 5.49 |
| 1017 | 2 | 3 | 3.49 |
| 1017 | 7 | 2 | 6.99 |
| 1018 | 1 | 80 | 4.79 |
| 1018 | 6 | 10 | 24.9 |
How the tables in the practice database fit together
Every table in the shop has a primary key, and the links between them are foreign keys:
| Table | Primary key | Foreign keys | Points to |
|---|---|---|---|
| customers | customer_id | ||
| products | product_id | ||
| orders | order_id | customer_id, employee_id | customers, employees |
| order_items | order_id and product_id together | order_id, product_id | orders, products |
This is how order_items is defined in the practice database:
CREATE TABLE order_items (
order_id INTEGER NOT NULL REFERENCES orders(order_id),
product_id INTEGER NOT NULL REFERENCES products(product_id),
quantity INTEGER NOT NULL,
unit_price REAL NOT NULL,
PRIMARY KEY (order_id, product_id)
);
The composite key means a product appears only once per order; more units simply go into quantity. The two foreign keys block line items for orders or products that don't exist.
Why keys are what make JOINs work
The orders table doesn't hold the customer's name, only their ID. A JOIN uses that ID to fetch the name from customers:
SELECT o.order_id, o.order_date, c.name
FROM orders o
JOIN customers c ON c.customer_id = o.customer_id
WHERE o.status = 'open';
| order_id | order_date | name |
|---|---|---|
| 1016 | 2026-06-12 | Daniel Kim |
| 1017 | 2026-06-13 | Raj Patel |
| 1018 | 2026-06-14 | Northline Printing Co |
This only works because customer_id is unique in customers (primary key) and every customer_id in orders points to a real customer (foreign key). If two customers shared ID 11, order 1016 would show up twice. If it pointed to a deleted customer, the JOIN would quietly drop it.
Primary keys
A primary key is unique and never empty, and a table can have at most one. Usually it's a running number with no meaning of its own. One SQLite quirk to know: apart from INTEGER PRIMARY KEY, it accepts NULL in key columns unless you add NOT NULL explicitly. That's why every key column in these exercises carries NOT NULL.
Foreign keys with REFERENCES
REFERENCES is followed by the table and column being pointed to, and that column has to be a primary key or UNIQUE. Try to add an order item for product 99, which doesn't exist, and the database rejects the row:
INSERT INTO order_items VALUES (1018, 99, 1, 9.99);
The exercise reports: “The row points to a record that does not exist (foreign key).” A foreign key holding NULL, on the other hand, isn't checked at all. If every row must belong to a record, the column needs NOT NULL too.
Task Customer service logs complaints. Create the table complaints: complaint_id (INTEGER PRIMARY KEY), order_id (whole number, required, foreign key to orders) and reason (text, required). To check it, the exercise adds a complaint for every shipped order, tries two incomplete complaints and shows in the column references_table which table your foreign key points to.
orders 18 rows, 5 columns
| order_id | customer_id | order_date | status | employee_id |
|---|---|---|---|---|
| 1001 | 1 | 2026-01-08 | delivered | 3 |
| 1002 | 4 | 2026-01-12 | delivered | 4 |
| 1003 | 3 | 2026-01-20 | delivered | 3 |
| 1004 | 7 | 2026-02-03 | delivered | 4 |
| 1005 | 2 | 2026-02-11 | cancelled | 8 |
| 1006 | 1 | 2026-02-25 | delivered | 3 |
| 1007 | 10 | 2026-03-04 | delivered | 2 |
| 1008 | 5 | 2026-03-17 | delivered | 4 |
| 1009 | 8 | 2026-03-30 | delivered | 3 |
| 1010 | 6 | 2026-04-07 | delivered | 8 |
| 1011 | 12 | 2026-04-22 | delivered | 4 |
| 1012 | 3 | 2026-05-06 | delivered | 3 |
| 1013 | 9 | 2026-05-19 | cancelled | 8 |
| 1014 | 7 | 2026-06-02 | shipped | 4 |
| 1015 | 1 | 2026-06-10 | shipped | 3 |
| 1016 | 11 | 2026-06-12 | open | NULL |
| 1017 | 4 | 2026-06-13 | open | NULL |
| 1018 | 10 | 2026-06-14 | open | NULL |
This exercise is part of Premium.
Premium unlocks every exercise in every lesson, unlimited practice with fresh tasks and the final test with certificate.
See Premium Already Premium? Log in
The first exercise in this lesson is free.
What happens on delete: ON DELETE
Try to delete a customer who still has orders and you run into the foreign key. What happens next is up to ON DELETE:
| Setting | When the customer is deleted … |
|---|---|
NO ACTION (the default) | the delete fails while dependent rows exist |
RESTRICT | the delete fails immediately |
CASCADE | the dependent rows are deleted too |
SET NULL | the reference in the dependent rows becomes NULL |
NO ACTION and RESTRICT differ in timing: RESTRICT checks right away, NO ACTION at the end of the statement, or at the end of the transaction if the check is deferred. CASCADE suits data that makes no sense without its parent, such as delivery addresses. For orders, blocking is the right call: sales records shouldn't vanish just because someone deleted a customer. The DELETE lesson has more on deleting rows.
Task Customers should be able to have several delivery addresses. Create the table delivery_addresses: address_id (INTEGER PRIMARY KEY), customer_id (whole number, required, foreign key to customers) and city (text). When a customer is deleted, their delivery addresses should be deleted automatically too. To check it, the exercise adds each customer's city as an address; the columns references_table and on_delete show how your foreign key is set up.
customers 12 rows, 7 columns
| customer_id | name | city | country | customer_since | segment | phone |
|---|---|---|---|---|---|---|
| 1 | Harbor Fremont Partners | Boston | USA | 2021-03-15 | Business | 617-555-0142 |
| 2 | Emily Carter | Chicago | USA | 2022-07-01 | Consumer | NULL |
| 3 | Riverside County Office | Riverside | USA | 2020-11-20 | Government | 951-555-0110 |
| 4 | Raj Patel | Leeds | UK | 2023-01-09 | Consumer | 0113 496 0123 |
| 5 | Lakeview Hotel Ltd | Manchester | UK | 2022-04-18 | Business | 0161 496 0456 |
| 6 | Olivia Brooks | Austin | USA | 2024-02-27 | Consumer | NULL |
| 7 | Greene & Shaw LLP | London | UK | 2021-09-05 | Business | 020 7946 0321 |
| 8 | Maple Grove High School | Austin | USA | 2023-08-14 | School | 512-555-0187 |
| 9 | Chloe Evans | Boston | USA | 2025-05-30 | Consumer | 617-555-0199 |
| 10 | Northline Printing Co | Toronto | Canada | 2020-06-12 | Business | 416-555-0133 |
| 11 | Daniel Kim | Seattle | USA | 2024-10-03 | Consumer | NULL |
| 12 | Westbrook Dental Clinic | Chicago | USA | 2022-12-01 | Business | 312-555-0164 |
This exercise is part of Premium.
Premium unlocks every exercise in every lesson, unlimited practice with fresh tasks and the final test with certificate.
See Premium Already Premium? Log in
The first exercise in this lesson is free.
Normalization in one paragraph
Normalizing means storing each fact in one place only. If every order carried the customer's name and city, a move would mean changing lots of rows, and missing one leaves your data contradicting itself. So the customer gets a table of their own, and the order only remembers the customer's ID. Primary and foreign keys are the tools for that, and JOIN puts the pieces back together when you query.
Common mistakes
PRIMARY KEY on two separate columns
Put PRIMARY KEY after both customer_id and product_id and the exercise reports “The database says: table "regular_items" has more than one primary key”. A two-column key goes at the end as PRIMARY KEY (customer_id, product_id).
A key on one column only
If the key in regular_items covers customer_id alone, each customer can only have one product. The exercise reports too few rows and asks whether the condition is too strict.
Pointing at the wrong column
If REFERENCES points to a column that is neither a primary key nor UNIQUE, such as REFERENCES orders(order_date), the first insert fails with “foreign key mismatch”.
Forgetting NOT NULL
Without NOT NULL, the table accepts a complaint with no order ID, because an empty foreign key counts as allowed. The exercise then reports one row too many.
Keys in MySQL, PostgreSQL, SQL Server and SQLite
| Database | ON DELETE | Default | Worth knowing |
|---|---|---|---|
| MySQL | CASCADE, SET NULL, RESTRICT, NO ACTION | NO ACTION, same as RESTRICT in InnoDB | InnoDB and NDB enforce foreign keys; both reject SET DEFAULT; an index on the foreign key column is created automatically |
| PostgreSQL | NO ACTION, RESTRICT, CASCADE, SET NULL, SET DEFAULT | NO ACTION | no automatic index on the foreign key column |
| SQL Server | NO ACTION, CASCADE, SET NULL, SET DEFAULT | NO ACTION | no RESTRICT in the syntax |
| SQLite (these exercises) | NO ACTION, RESTRICT, SET NULL, SET DEFAULT, CASCADE | NO ACTION | foreign keys stay off until each connection runs PRAGMA foreign_keys = ON; in the exercises they're on |
PostgreSQL and SQLite both recommend indexing the foreign key column yourself, because otherwise a delete in the parent table has to scan the whole child table.
Sources: MySQL Reference Manual (FOREIGN KEY Constraints), PostgreSQL documentation (Constraints), Microsoft Learn (CREATE TABLE), sqlite.org (SQLite Foreign Key Support, CREATE TABLE).
Frequently asked questions
Does every table need a primary key?
Not always technically, but almost always in practice. Without one you can't reliably point at a specific row, and other tables can't reference it.
A number or a real value as the key?
An email address looks unique, but it changes, and then every reference would have to change with it. A number with no meaning of its own stays the same forever. Real values that must be unique can get a UNIQUE rule on top.
Do keys make queries faster?
The primary key gets an index that lets the database find a row quickly. Foreign keys don't get one automatically everywhere; see the table above.
What does ON UPDATE do?
The same as ON DELETE, but for when the ID in the parent table changes. With running numbers that never change, you'll rarely need it.