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_idcustomer_idorder_datestatusemployee_id
100112026-01-08delivered3
100242026-01-12delivered4
100332026-01-20delivered3
100472026-02-03delivered4
100522026-02-11cancelled8
100612026-02-25delivered3
1007102026-03-04delivered2
100852026-03-17delivered4
100982026-03-30delivered3
101062026-04-07delivered8
1011122026-04-22delivered4
101232026-05-06delivered3
101392026-05-19cancelled8
101472026-06-02shipped4
101512026-06-10shipped3
1016112026-06-12openNULL
101742026-06-13openNULL
1018102026-06-14openNULL
order_items 38 rows, 4 columns
order_idproduct_idquantityunit_price
10011404.79
10013252.79
10016424.9
1002223.49
10021035.49
10031604.69
100311684.9
10033502.59
100443179
100493269
100551449
10061304.79
10067106.99
100782219
100711489.9
10071204.99
100846175
1008253.49
1009101204.99
10092403.19
100992279
1010726.99
1010213.49
1011121129
10111104.99
10113122.79
10126823.9
10121404.69
101391279
101452439
101442179
10151504.79
101511289.9
10161045.49
1017233.49
1017726.99
10181804.79
101861024.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:

TablePrimary keyForeign keysPoints to
customerscustomer_id
productsproduct_id
ordersorder_idcustomer_id, employee_idcustomers, employees
order_itemsorder_id and product_id togetherorder_id, product_idorders, 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_idorder_datename
10162026-06-12Daniel Kim
10172026-06-13Raj Patel
10182026-06-14Northline 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_idcustomer_idorder_datestatusemployee_id
100112026-01-08delivered3
100242026-01-12delivered4
100332026-01-20delivered3
100472026-02-03delivered4
100522026-02-11cancelled8
100612026-02-25delivered3
1007102026-03-04delivered2
100852026-03-17delivered4
100982026-03-30delivered3
101062026-04-07delivered8
1011122026-04-22delivered4
101232026-05-06delivered3
101392026-05-19cancelled8
101472026-06-02shipped4
101512026-06-10shipped3
1016112026-06-12openNULL
101742026-06-13openNULL
1018102026-06-14openNULL

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:

SettingWhen the customer is deleted …
NO ACTION (the default)the delete fails while dependent rows exist
RESTRICTthe delete fails immediately
CASCADEthe dependent rows are deleted too
SET NULLthe 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_idnamecitycountrycustomer_sincesegmentphone
1Harbor Fremont PartnersBostonUSA2021-03-15Business617-555-0142
2Emily CarterChicagoUSA2022-07-01ConsumerNULL
3Riverside County OfficeRiversideUSA2020-11-20Government951-555-0110
4Raj PatelLeedsUK2023-01-09Consumer0113 496 0123
5Lakeview Hotel LtdManchesterUK2022-04-18Business0161 496 0456
6Olivia BrooksAustinUSA2024-02-27ConsumerNULL
7Greene & Shaw LLPLondonUK2021-09-05Business020 7946 0321
8Maple Grove High SchoolAustinUSA2023-08-14School512-555-0187
9Chloe EvansBostonUSA2025-05-30Consumer617-555-0199
10Northline Printing CoTorontoCanada2020-06-12Business416-555-0133
11Daniel KimSeattleUSA2024-10-03ConsumerNULL
12Westbrook Dental ClinicChicagoUSA2022-12-01Business312-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

DatabaseON DELETEDefaultWorth knowing
MySQLCASCADE, SET NULL, RESTRICT, NO ACTIONNO ACTION, same as RESTRICT in InnoDBInnoDB and NDB enforce foreign keys; both reject SET DEFAULT; an index on the foreign key column is created automatically
PostgreSQLNO ACTION, RESTRICT, CASCADE, SET NULL, SET DEFAULTNO ACTIONno automatic index on the foreign key column
SQL ServerNO ACTION, CASCADE, SET NULL, SET DEFAULTNO ACTIONno RESTRICT in the syntax
SQLite (these exercises)NO ACTION, RESTRICT, SET NULL, SET DEFAULT, CASCADENO ACTIONforeign 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.

Up next: views

Need that orders-and-customers JOIN all the time? Save it as a view and query it like a table.

Practice views

Write to us

Choose language

Select your preferred language