Sub topic 1
How tables relate: primary keys and foreign keys
An inner join pairs rows from two tables by comparing values in their columns. Those columns are usually a primary key on one side and a foreign key on the other. This chapter covers how that pairing is stored, what the database does and does not enforce, and how the design decides which rows a join can match.
Prerequisites
This chapter assumes you can:
- Write a basic
SELECT ... FROM ... WHERE ... ORDER BYquery. - Describe a table as rows (records) and columns (fields).
- Run SQL against a database such as PostgreSQL, MySQL, SQL Server or SQLite. The examples use standard SQL.
You do not need to know any join syntax yet. The next chapters introduce it.
Primary keys: identifying a row
A primary key is a column, or a set of columns, whose value identifies exactly one row in a table. The database enforces two rules on it:
- Values must be unique. No two rows can share the same key.
- Values cannot be NULL. Every row must have a key.
Because of these rules, you can always point at one specific row by its key. customers.id = 2 means Ben and nobody else.
Many designs use a meaningless number as the key, such as 1, 2, 3. A number that is never reused and never changes is safer than a natural value like an email address, which can change.
Foreign keys: pointing at another row
A foreign key is a column in one table that stores the primary key value of a row in another table. The table that holds the foreign key is the child table. The table it points to is the parent table.
In the sample schema, orders.customer_id is a foreign key to customers.id. Order 101 stores customer_id = 1, which means "this order belongs to the customer whose id is 1."
CREATE TABLE customers (
id INTEGER PRIMARY KEY,
name VARCHAR(100) NOT NULL
);
CREATE TABLE orders (
id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (id),
order_date DATE NOT NULL,
total DECIMAL(10, 2) NOT NULL
);
INSERT INTO customers (id, name) VALUES (1, 'Ada'), (2, 'Ben'), (3, 'Chloe');
INSERT INTO orders (id, customer_id, order_date, total) VALUES
(101, 1, '2026-01-05', 50.00),
(102, 1, '2026-02-10', 75.00),
(103, 2, '2026-02-11', 20.00),
(104, NULL, '2026-03-01', 99.00);This schema is used throughout the tutorial. Two details are deliberate:
- Chloe (customer 3) has no orders.
- Order 104 has a NULL
customer_id, so it belongs to nobody.
Later chapters show how these two rows behave in joins. For now, notice that the schema allows both.
Reading the relationship
The relationship between customers and orders is one-to-many:
- One customer can have many orders. Ada has two.
- Each order points to at most one customer, because
customer_idholds a single value.
The "many" side always holds the foreign key. You never store a list of order IDs inside a customer row. Instead, each order points back to its customer. This is why a join on these tables compares orders.customer_id with customers.id.
The symbols in the diagram encode this. |o on the left means a customer is the parent, and o{ on the right means zero or more orders. The o next to the order side exists because the foreign key is nullable.
Other relationship shapes build on the same mechanism:
| Shape | How it is stored | Example |
|---|---|---|
| One-to-many | Foreign key on the "many" table | Customer to orders |
| One-to-one | Foreign key that is also unique | User to profile |
| Many-to-many | A linking table with two foreign keys | Orders to products, through `order_items` |
The many-to-many case appears in the chapter on joining three or more tables.
What the database enforces
A foreign key is a constraint, a rule the database checks on every change. It guarantees that a non-NULL value in orders.customer_id matches an existing customers.id. Try to break the rule and the statement fails:
-- Fails: there is no customer with id 99.
INSERT INTO orders (id, customer_id, order_date, total)
VALUES (105, 99, '2026-03-02', 10.00);
-- Fails: orders 101 and 102 still point at customer 1.
DELETE FROM customers WHERE id = 1;The exact error text differs by database, but both statements are rejected. The second one shows that the rule works in both directions. You cannot create a child that points nowhere, and by default you cannot delete a parent that still has children.
You can change the delete behavior when you declare the key, for example with ON DELETE CASCADE (delete the children too) or ON DELETE SET NULL (keep the children and clear the pointer). The default is the safest choice. Pick the others deliberately.
What the database does not enforce
A foreign key does not require that every parent has a child, and it does not stop NULL values unless you add NOT NULL. Both facts matter for joins:
- Chloe has no orders. A foreign key never forces a customer to have any.
- Order 104 has no customer. A NULL is not a reference to anything, so the constraint skips it.
Making customer_id NOT NULL would remove the second case. Whether to do so is a design decision. An order that must always belong to a customer should be declared that way.
Finding rows that will not match
Before you write a join, you can check where the data has gaps. These two queries find the unmatched rows in the sample data.
-- Orders with no customer.
SELECT id, total
FROM orders
WHERE customer_id IS NULL;
-- Customers with no orders.
SELECT c.id, c.name
FROM customers AS c
WHERE NOT EXISTS (
SELECT 1 FROM orders AS o WHERE o.customer_id = c.id
);The first returns order 104. The second returns Chloe. Notice that the first query uses IS NULL. Writing customer_id = NULL returns no rows, because comparing anything to NULL gives "unknown" rather than true. The chapter on NULL keys covers this in detail.
These are exactly the rows an inner join leaves out. Knowing they exist before you join saves you from wondering later why a count is lower than expected.
Common errors
- Assuming a foreign key is indexed. Primary keys get an index automatically in every major database. Foreign keys usually do not, except in MySQL's InnoDB engine. Joins and parent deletes on an unindexed foreign key can be slow. The performance chapter returns to this.
- Joining on columns that are not keys. Matching
orders.totalto some other number compiles fine but means nothing. Join along declared relationships unless you have a reason not to. - Mismatched types. A foreign key must have a type compatible with the key it references. An
INTEGERpointing to aVARCHARis rejected by some databases and silently converted by others, which can hurt index use. - Forgetting the relationship exists only if declared. Two columns named
customer_idandidare related only by convention until aREFERENCESclause says so. Without one, nothing stops bad values. - Confusing the direction. The foreign key sits on the child. If you cannot tell which table is the parent, ask which table can exist without the other.
Why this matters for inner joins
An inner join returns a row only when a value in one table matches a value in the other. With a primary key and foreign key pair, the match is predictable:
- Each child row matches at most one parent, because the key is unique.
- Each parent row can match zero, one or many children.
- A child with a NULL foreign key matches nothing.
These three facts explain most surprises you will meet in later chapters: missing rows, repeated rows, and totals that come out too high.
Exercise
In the sample schema, order 104 has a NULL customerid and customer 3 (Chloe) has no orders. Does the foreign key on orders.customerid allow both situations, and which table is the child?
Show answer
Yes, both are allowed. A foreign key only checks that non-NULL values match an existing customers.id, so NULL is skipped and a parent is not required to have children. The orders table is the child because it holds the foreign key; customers is the parent.
Exercise
Write a query that lists the id and total of every order whose customer_id points to a customer who does not exist. Will it return rows for the sample data when the foreign key is enforced?
Show answer
SELECT o.id, o.total FROM orders AS o WHERE o.customerid IS NOT NULL AND NOT EXISTS (SELECT 1 FROM customers AS c WHERE c.id = o.customerid); It returns no rows when the foreign key is enforced, because the constraint rejects any non-NULL customer_id without a matching customer.