Lab 11: Primary Keys, Foreign Keys & Constraints

Time: 30 minutes | Level: Foundations | DB: MySQL 8 / PostgreSQL 15

Overview

Learn PRIMARY KEY, FOREIGN KEY with ON DELETE options, UNIQUE, CHECK constraints, composite keys, and how to inspect constraints in the database catalog.


Step 1: Setup

docker run -d --name mysql-lab -e MYSQL_ROOT_PASSWORD=rootpass mysql:8.0
for i in $(seq 1 30); do docker exec mysql-lab mysql -uroot -prootpass -e "SELECT 1" 2>/dev/null && break || sleep 2; done

docker run -d --name pg-lab -e POSTGRES_PASSWORD=rootpass postgres:15
sleep 10

Step 2: PRIMARY KEY

docker exec mysql-lab mysql -uroot -prootpass << 'EOF'
CREATE DATABASE constraintlab;
USE constraintlab;

-- Single-column primary key
CREATE TABLE users (
    user_id    INT          NOT NULL AUTO_INCREMENT,
    username   VARCHAR(50)  NOT NULL,
    email      VARCHAR(100) NOT NULL,
    created_at TIMESTAMP    DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (user_id)
);

-- Attempt to insert duplicate PK
INSERT INTO users (username, email) VALUES ('alice', '[email protected]');
INSERT INTO users (username, email) VALUES ('bob',   '[email protected]');

-- This will fail: duplicate PK
INSERT INTO users (user_id, username, email) VALUES (1, 'dup', '[email protected]');
EOF

📸 Verified Output (duplicate PK error):

💡 PRIMARY KEY combines NOT NULL + UNIQUE. It uniquely identifies each row. A table can have only ONE primary key, but it can span multiple columns (composite PK).


Step 3: UNIQUE Constraint

📸 Verified Output:


Step 4: FOREIGN KEY with ON DELETE Options

📸 Verified Output:


Step 5: CHECK Constraints

📸 Verified Output:


Step 6: Composite Primary Key

📸 Verified Output:


Step 7: Inspect Constraints (MySQL and PostgreSQL)

MySQL:

📸 Verified Output:

PostgreSQL — pg_constraints:


Step 8: Capstone — Full Schema with All Constraint Types

📸 Verified Output:

Cleanup:


Summary

Constraint
Purpose
NULL allowed?

PRIMARY KEY

Unique row identifier

No

FOREIGN KEY

Referential integrity

Yes (optional FK)

UNIQUE

No duplicate values

Yes (multiple NULLs OK)

NOT NULL

Must have a value

N/A

CHECK

Custom validation expression

Yes

DEFAULT

Fallback value

N/A

ON DELETE Option
Effect

CASCADE

Delete child rows

SET NULL

Set FK column to NULL

RESTRICT

Block parent deletion

NO ACTION

Same as RESTRICT (default)

SET DEFAULT

Set FK to default value

Next: Lab 12 — Indexes Basics

Last updated