Aral Code

Designing Databases Lesson 5 of 13

MySQL Keys — Primary Keys, Foreign Keys and Indexes

Link tables with primary and foreign keys, use AUTO_INCREMENT, choose ON DELETE behavior, add UNIQUE constraints and indexes, and read EXPLAIN.

Keys are what make a database relational. A primary key identifies each row; a foreign key links a row to a row in another table; an index makes searching fast.

Primary keys

CREATE TABLE sections (
  id SMALLINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(30) NOT NULL,
  grade_level TINYINT UNSIGNED NOT NULL,
  UNIQUE (name, grade_level)
);
  • Every table should have a primary key: unique and never NULL.
  • AUTO_INCREMENT lets MySQL assign 1, 2, 3… automatically.
  • UNIQUE (name, grade_level) prevents two "Rizal" sections in the same grade, while allowing Grade 7 Rizal and Grade 8 Rizal.

After inserting, SELECT LAST_INSERT_ID(); returns the id MySQL just created.

Foreign keys

CREATE TABLE students (
  id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(80) NOT NULL,
  section_id SMALLINT UNSIGNED NOT NULL,
  FOREIGN KEY (section_id) REFERENCES sections(id)
    ON UPDATE CASCADE
    ON DELETE RESTRICT
);

Now MySQL guarantees that every student's section_id matches an existing section. Trying to insert a student into section 99 when it doesn't exist fails:

Error

ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails

The foreign key column must have exactly the same type as the referenced column (here, both SMALLINT UNSIGNED), and both tables must use the InnoDB engine.

ON DELETE options

OptionWhen the parent row is deleted…Example
RESTRICT (default)Refuse, while children existCan't delete a section that still has students
CASCADEDelete the children tooDeleting an order deletes its order items
SET NULLSet the children's key to NULLDeleting an adviser leaves the section without one

See foreign keys in action

The live editor (SQLite) enforces foreign keys after PRAGMA foreign_keys = ON;, which MySQL's InnoDB does automatically:

SQL A foreign key blocks bad data
PRAGMA foreign_keys = ON;
CREATE TABLE sections (id INTEGER PRIMARY KEY, name TEXT NOT NULL);
CREATE TABLE learners (
  id INTEGER PRIMARY KEY,
  name TEXT NOT NULL,
  section_id INTEGER NOT NULL REFERENCES sections(id)
);
INSERT INTO sections (name) VALUES ('Rizal'), ('Mabini');
INSERT INTO learners (name, section_id) VALUES ('Ana', 1), ('Ben', 2);
SELECT l.name, s.name AS section FROM learners l JOIN sections s ON s.id = l.section_id;
-- Remove the -- below to see the foreign key refuse section 99:
-- INSERT INTO learners (name, section_id) VALUES ('Cy', 99);

Indexes

An index works like a book's index: MySQL can jump straight to matching rows instead of reading the whole table.

CREATE INDEX idx_students_name ON students (name);
CREATE INDEX idx_orders_date ON orders (order_date);
SHOW INDEX FROM students;
  • Primary keys, UNIQUE columns and foreign keys get indexes automatically.
  • Add indexes on columns you often search, join or sort by.
  • Don't index everything: each index uses space and slows down inserts and updates a little.

EXPLAIN: is my query using an index?

EXPLAIN SELECT * FROM students WHERE name = 'Ana Reyes';

Output

+----+-------------+----------+------+-------------------+-------------------+---------+-------+------+-------+
| id | select_type | table    | type | possible_keys     | key               | key_len | ref   | rows | Extra |
+----+-------------+----------+------+-------------------+-------------------+---------+-------+------+-------+
|  1 | SIMPLE      | students | ref  | idx_students_name | idx_students_name | 322     | const | 1    |       |
+----+-------------+----------+------+-------------------+-------------------+---------+-------+------+-------+

The key column shows the index used and rows how many rows MySQL expects to read. If type says ALL, MySQL is scanning the whole table; consider an index.

Quick Quiz

Check what you learned. Walang grade ito, practice lang. 🙂

1. What does a foreign key guarantee?
2. What does ON DELETE CASCADE do?
3. Which columns get an index automatically?
4. What does EXPLAIN show?

By Sir Reyel · Last updated 2026-12-04