TExcelTAD
Home › MySQL › MySQL PRIMARY KEY and FOREIGN KEY

MySQL PRIMARY KEY and FOREIGN KEY

Keys are what make a database relational. A primary key identifies each row of a table; a foreign key links a row to a row in another table.

PRIMARY KEY

A primary key is a column (or set of columns) whose value is unique and never NULL. Each table can have only one, and every InnoDB table should have one: InnoDB stores the rows in primary-key order, so it is also the fastest way to find a row.

mysql · try it yourself
CREATE TABLE coupons (
  code       VARCHAR(12) PRIMARY KEY,
  percent    TINYINT NOT NULL,
  valid_till DATE NOT NULL
);
INSERT INTO coupons VALUES ('SPRING10', 10, '2025-05-31'), ('VIP25', 25, '2025-12-31');
SELECT * FROM coupons WHERE code = 'vip25';
+-------+---------+------------+
| code  | percent | valid_till |
+-------+---------+------------+
| VIP25 |      25 | 2025-12-31 |
+-------+---------+------------+

A second row with 'SPRING10' would fail with Duplicate entry 'SPRING10' for key 'PRIMARY' (MySQL 8 names the key 'coupons.PRIMARY'). The lookup with 'vip25' found the row because the key column uses a case-insensitive collation: for this table 'VIP25' and 'vip25' are the same key.

Natural or surrogate key?

code is a natural key: a real-world value. Most tables instead use a surrogate key, a meaningless number such as customer_id INT AUTO_INCREMENT PRIMARY KEY. Surrogate keys never need to change (people change e-mail addresses and names), they are small, and they make foreign keys simple. Keep the natural value unique with a UNIQUE constraint.

Composite primary keys

A primary key can span several columns. order_details uses (order_id, product_id): an order can contain many products and a product can be in many orders, but each product appears at most once per order.

mysql · try it yourself
INSERT IGNORE INTO order_details (order_id, product_id, quantity, unit_price)
VALUES (1, 2, 1, 6.75),    -- new combination: ok
       (1, 1, 5, 24.50);   -- order 1 already has product 1: skipped
SELECT order_id, product_id, quantity FROM order_details WHERE order_id = 1 ORDER BY product_id;
+----------+------------+----------+
| order_id | product_id | quantity |
+----------+------------+----------+
|        1 |          1 |        1 |
|        1 |          2 |        1 |
|        1 |          6 |        4 |
|        1 |          9 |        2 |
+----------+------------+----------+

FOREIGN KEY

A foreign key says "the value in this column must exist as a key in that table". It prevents orphans: orders for customers that don't exist, products in categories that don't exist.

sql
CREATE TABLE orders (
  ...
  customer_id INT NOT NULL,
  FOREIGN KEY (customer_id) REFERENCES customers (customer_id)
);

The table with the foreign key is the child (orders), the referenced table the parent (customers). The parent column must be a primary key or unique, and both columns need the same type. MySQL enforces foreign keys only in the InnoDB engine, which is the default.

mysql · try it yourself
INSERT INTO orders (customer_id, employee_id, order_date, status)
VALUES (3, 4, '2025-06-05', 'processing');
SELECT order_id, customer_id FROM orders WHERE order_date = '2025-06-05';
INSERT INTO orders (customer_id, employee_id, order_date, status)
VALUES (42, 4, '2025-06-05', 'processing');
+----------+-------------+
| order_id | customer_id |
+----------+-------------+
|       23 |           3 |
+----------+-------------+
ERROR 1452 (23000) at line 4: Cannot add or update a child row: a foreign key constraint fails (`shop`.`orders`, CONSTRAINT `orders_ibfk_1` FOREIGN KEY (`customer_id`) REFERENCES `customers` (`customer_id`))

Customer 3 exists, customer 42 doesn't. The error names the constraint (orders_ibfk_1, generated automatically) and the columns.

ON DELETE and ON UPDATE

What should happen to the children when a parent row is deleted or its key changes? You choose with referential actions:

Action Effect on child rows
RESTRICT / NO ACTION (default) refuse the delete/update while children exist
CASCADE delete the children too (or update their foreign key)
SET NULL set the child's foreign key column to NULL
mysql · try it yourself
CREATE TABLE wishlists (
  wishlist_id INT AUTO_INCREMENT PRIMARY KEY,
  customer_id INT NOT NULL,
  title       VARCHAR(40),
  CONSTRAINT fk_wishlist_customer
    FOREIGN KEY (customer_id) REFERENCES customers (customer_id)
    ON DELETE CASCADE
);
CREATE TABLE wishlist_items (
  wishlist_id INT NOT NULL,
  product_id  INT,
  FOREIGN KEY (wishlist_id) REFERENCES wishlists (wishlist_id) ON DELETE CASCADE,
  FOREIGN KEY (product_id)  REFERENCES products (product_id)   ON DELETE SET NULL
);
INSERT INTO wishlists (customer_id, title) VALUES (7, 'Birthday'), (13, 'Pantry');
INSERT INTO wishlist_items VALUES (1, 1), (1, 7), (2, 4);

DELETE FROM products WHERE product_id = 4;   -- never sold, so this is allowed
DELETE FROM customers WHERE customer_id = 7; -- no orders, but has a wishlist

SELECT * FROM wishlists;
SELECT * FROM wishlist_items;
+-------------+-------------+--------+
| wishlist_id | customer_id | title  |
+-------------+-------------+--------+
|           2 |          13 | Pantry |
+-------------+-------------+--------+
+-------------+------------+
| wishlist_id | product_id |
+-------------+------------+
|           2 |       NULL |
+-------------+------------+

Deleting George (7) cascaded to his wishlist and from there to its items. Deleting product 4 set product_id to NULL in Mia's wishlist item instead.

Tip: Use CASCADE for rows that only make sense with their parent (order lines, wishlist items). Keep the default RESTRICT for important history: you don't want deleting a customer to silently erase their orders.

Adding and dropping keys later

sql
ALTER TABLE coupons ADD PRIMARY KEY (code);
ALTER TABLE coupons DROP PRIMARY KEY;
ALTER TABLE reviews ADD CONSTRAINT fk_review_product
  FOREIGN KEY (product_id) REFERENCES products (product_id);
ALTER TABLE reviews DROP FOREIGN KEY fk_review_product;

Test yourself

Which statement about a PRIMARY KEY is true?

  1. A table can have several
  2. Its values must be unique and not NULL
  3. It must be an integer
  4. It must be the first column

With ON DELETE CASCADE, what happens to child rows when their parent is deleted?

  1. The delete is refused
  2. They are deleted too
  3. Their key becomes NULL
  4. Nothing

What is the default foreign-key behaviour when you delete a parent row that still has children?

  1. CASCADE
  2. SET NULL
  3. The delete is refused (RESTRICT / NO ACTION)
  4. The children are moved to another parent