← Retour au cours: SQL and databases from scratch

Primary and foreign keys: how tables relate

Vidéo bientôt disponible

We have reached the idea that gives relational databases their name. Until now you queried one table at a time, but useful information is almost always spread out: the customer's name is in customers, and what they bought is in orders and order_items. To combine it, tables need a safe way of pointing at each other. That way is primary keys and foreign keys.

Primary key (PRIMARY KEY)

The primary key is the column, or set of columns, that uniquely identifies each row of a table. It meets three conditions: it never repeats, it is never NULL and it should not change over time. In customers it is customer_id; in products, product_id. We use numbers with no meaning of their own (surrogate keys) instead of real data such as the email, because real data changes: if Ana changes her email and the email were the key, it would have to be fixed everywhere it is referenced.

Foreign key (FOREIGN KEY)

A foreign key is a column that stores the value of the primary key of another table. In orders, the customer_id column holds the number of the customer who placed the order: it points to customers.customer_id. The database watches this relationship: it does not let you create an order for a customer that does not exist, nor delete a customer who still has orders. This is called referential integrity, and it is one of the great advantages of relational databases over a spreadsheet.

sql
-- Reading the relationship by hand: first the customer...
SELECT customer_id, name FROM customers WHERE name = 'Ana Silva';

-- ...then her orders, using the number we found (customer_id = 1)
SELECT order_id, order_date, status FROM orders WHERE customer_id = 1;

-- The foreign key protects us: there is no customer 99
-- INSERT INTO orders (order_id, customer_id, order_date, status)
-- VALUES (13, 99, '2024-08-01', 'pending');
-- ERROR: insert or update on table "orders" violates foreign key constraint

Types of relationship

  • One to many (1:N): a customer has many orders; each order belongs to one customer. It is the most common and is implemented with a foreign key on the many side.
  • Many to many (N:M): an order has many products and a product appears in many orders. It is implemented with a junction table, here order_items, which has two foreign keys.
  • One to one (1:1): uncommon; it is used to separate optional or sensitive data into another table.

Look at our schema through that lens. customers relates 1:N to orders through orders.customer_id. orders relates 1:N to order_items through order_items.order_id. products relates 1:N to order_items through order_items.product_id. Therefore, between orders and products there is an N:M relationship whose bridge is order_items. We store unit_price in the order line, and not only in products, because a product's price can change and the historical order must keep what was actually charged.

sql
-- Which orders contain product 2 (Wireless Mouse)? The bridge table answers it.
SELECT order_id, quantity, unit_price FROM order_items WHERE product_id = 2;

-- How many lines does each order have?
SELECT order_id, COUNT(*) AS lines FROM order_items GROUP BY order_id ORDER BY order_id;

✎ Mes notes

Enregistré seulement dans ce navigateur. Connectez-vous pour le garder dans votre compte.0/5000 caractères

← PrécédenteSuivante →