Lab 11: Primary Keys, Foreign Keys & Constraints
Overview
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 10Step 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]');
EOFStep 3: UNIQUE Constraint
Step 4: FOREIGN KEY with ON DELETE Options
Step 5: CHECK Constraints
Step 6: Composite Primary Key
Step 7: Inspect Constraints (MySQL and PostgreSQL)
Step 8: Capstone — Full Schema with All Constraint Types
Summary
Constraint
Purpose
NULL allowed?
ON DELETE Option
Effect
Last updated
