MySQL Constraints, Foreign Keys and ALTER TABLE

MySQL 60 min min read Updated: Nov 27, 2026 Intermediate
MySQL Constraints, Foreign Keys and ALTER TABLE
Intermediate Topic 3 of 3

A Table with Rules

sql CREATE TABLE employees ( id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY, email VARCHAR(100) NOT NULL, salary DECIMAL(10,2) NOT NULL, status ENUM('active', 'on_leave', 'left') NOT NULL DEFAULT 'active', hired DATE NOT NULL, CONSTRAINT uq_employees_email UNIQUE (email), CONSTRAINT ck_employees_salary CHECK (salary > 0) ); INSERT INTO employees (email, salary, hired) VALUES ('a@corp.com', 50000, '2025-01-01'); SELECT id, email, salary, status FROM employees;

Result:

idemailsalarystatus
1a@corp.com50000.00active

Naming constraints (uq_..., ck_...) makes error messages and later changes easier.

What Happens When a Rule Breaks

sql CREATE TABLE employees (id INT AUTO_INCREMENT PRIMARY KEY, email VARCHAR(100) NOT NULL, salary DECIMAL(10,2) NOT NULL, CONSTRAINT uq_employees_email UNIQUE (email), CONSTRAINT ck_employees_salary CHECK (salary > 0)); INSERT INTO employees (email, salary) VALUES ('a@corp.com', 50000); INSERT INTO employees (email, salary) VALUES ('a@corp.com', 40000);
UNIQUE

ERROR 1062: Duplicate entry 'a@corp.com' for key 'employees.uq_employees_email'

sql CREATE TABLE employees (id INT AUTO_INCREMENT PRIMARY KEY, email VARCHAR(100) NOT NULL, salary DECIMAL(10,2) NOT NULL, CONSTRAINT uq_employees_email UNIQUE (email), CONSTRAINT ck_employees_salary CHECK (salary > 0)); INSERT INTO employees (email, salary) VALUES ('b@corp.com', -5);
CHECK

ERROR 3819: Check constraint 'ck_employees_salary' is violated.

sql CREATE TABLE employees (id INT AUTO_INCREMENT PRIMARY KEY, email VARCHAR(100) NOT NULL, salary DECIMAL(10,2) NOT NULL); INSERT INTO employees (salary) VALUES (1000);
NOT NULL

ERROR 1364: Field 'email' doesn't have a default value

The NOT NULL error says "doesn't have a default value" because the column was left out of the insert. Naming the column with an explicit NULL gives error 1048 instead. Either way the row is refused in strict mode.

CHECK needs MySQL 8.0.16 or later Older MySQL (5.7 and 8.0.15 and before) accepted the CHECK syntax and silently ignored it. This is a common surprise when moving a database between versions.

FOREIGN KEY Actions

Foreign keys need InnoDB. Choose what happens to child rows when the parent changes:

OptionOn DELETE or UPDATE of parent
RESTRICT / NO ACTION (default)Refuse the change
CASCADEApply the same change to the children
SET NULLSet the child column to NULL (the column must allow NULL)
SET DEFAULTNot supported by InnoDB
sql CREATE TABLE authors (id INT PRIMARY KEY, name VARCHAR(30)); CREATE TABLE books ( id INT PRIMARY KEY, title VARCHAR(50), author_id INT NULL, CONSTRAINT fk_books_author FOREIGN KEY (author_id) REFERENCES authors(id) ON DELETE SET NULL ON UPDATE CASCADE ); INSERT INTO authors VALUES (1, 'Orwell'), (2, 'Austen'); INSERT INTO books VALUES (1, '1984', 1), (2, 'Emma', 2); DELETE FROM authors WHERE id = 1; UPDATE authors SET id = 20 WHERE id = 2; SELECT id, title, author_id FROM books ORDER BY id;

Result:

idtitleauthor_id
11984NULL
2Emma20

Deleting Orwell set the book's author_id to NULL. Changing Austen's id to 20 updated the book automatically.

sql INSERT INTO orders VALUES (50, 99, '2025-07-01', 'pending');
Foreign key blocks unknown parent

ERROR 1452: Cannot add or update a child row: a foreign key constraint fails ('shop'.'orders', CONSTRAINT 'orders_ibfk_1' FOREIGN KEY ('customer_id') REFERENCES 'customers' ('id'))

Disabling Foreign Key Checks

During imports MySQL files often start with SET FOREIGN_KEY_CHECKS = 0;. It lets you load tables in any order, but it also lets bad data in. Turn it back on and verify the data after the import.

sql SET FOREIGN_KEY_CHECKS = 0; INSERT INTO orders VALUES (50, 99, '2025-07-01', 'pending'); SET FOREIGN_KEY_CHECKS = 1; SELECT o.id AS orphan_order FROM orders o LEFT JOIN customers c ON c.id = o.customer_id WHERE c.id IS NULL;

Result:

orphan_order
50
Orphans stay Turning checks back on does not remove or flag the bad row. The query above finds orphan orders. Always verify after a bulk load.

ALTER TABLE: Changing the Structure

TaskStatement
Add a columnALTER TABLE t ADD COLUMN phone VARCHAR(20) AFTER email;
Change a typeALTER TABLE t MODIFY COLUMN phone VARCHAR(30) NOT NULL;
Rename a columnALTER TABLE t RENAME COLUMN phone TO mobile;
Drop a columnALTER TABLE t DROP COLUMN mobile;
Rename a tableRENAME TABLE t TO t_new;
Add an indexALTER TABLE t ADD INDEX idx_city (city);
Add a foreign keyALTER TABLE t ADD CONSTRAINT fk_x FOREIGN KEY (c) REFERENCES p(id);
Drop a foreign keyALTER TABLE t DROP FOREIGN KEY fk_x;
Drop a checkALTER TABLE t DROP CHECK ck_x;
sql ALTER TABLE products ADD COLUMN sku VARCHAR(20) NULL AFTER name; ALTER TABLE products ADD UNIQUE INDEX uq_products_sku (sku); ALTER TABLE products MODIFY COLUMN name VARCHAR(150) NOT NULL; ALTER TABLE products RENAME COLUMN stock TO units_in_stock; ALTER TABLE products ADD CONSTRAINT ck_products_price CHECK (price >= 0); SELECT id, name, sku, units_in_stock FROM products WHERE id <= 2 ORDER BY id;

Result:

idnameskuunits_in_stock
1LaptopNULL15
2PhoneNULL30

Look at the structure afterwards:

sql ALTER TABLE products ADD COLUMN sku VARCHAR(20) NULL AFTER name; DESCRIBE products;

Result:

FieldTypeNullKeyDefaultExtra
idintNOPRINULL(empty)
namevarchar(100)NO(empty)NULL(empty)
skuvarchar(20)YES(empty)NULL(empty)
categoryvarchar(50)NO(empty)NULL(empty)
pricedecimal(10,2)NO(empty)NULL(empty)
stockintNO(empty)NULL(empty)
sql ALTER TABLE products ADD CONSTRAINT ck_products_price CHECK (price >= 0); UPDATE products SET price = -1 WHERE id = 1;
Error

ERROR 3819: Check constraint 'ck_products_price' is violated.

sql ALTER TABLE products ADD COLUMN price DECIMAL(5,2);
Duplicate column

ERROR 1060: Duplicate column name 'price'

Big Tables: Online DDL

ALTER TABLE on a table with millions of rows can take a long time and block writes. InnoDB supports online DDL for many changes. State your wish explicitly, and MySQL refuses if it cannot comply instead of silently locking:

sql ALTER TABLE big_table ADD COLUMN note VARCHAR(50) NULL, ALGORITHM=INSTANT; ALTER TABLE big_table ADD INDEX idx_created (created), ALGORITHM=INPLACE, LOCK=NONE;

INSTANT adds a column in 8.0 without rebuilding the table. For changes that need a full rebuild, tools such as gh-ost or pt-online-schema-change copy the table in the background. Always test on a copy of production data first (these statements were not run on a big table here).

Common Beginner Mistakes

MistakeWhat happensFix
Unnamed constraintsHard to drop laterName them fk_, uq_, ck_
Using MyISAM tables with foreign keysKeys are ignoredUse InnoDB (the default)
Leaving FOREIGN_KEY_CHECKS=0Orphan rows appearTurn it back on and verify
ALTER TABLE on a huge table during peak hoursLong locksOnline DDL or a migration tool, off-peak
Expecting CHECK to work on old versionsRules silently ignoredUse MySQL 8.0.16+
Forgetting NOT NULL when using MODIFYColumn becomes nullable againRepeat the full definition

Practice

  1. Add a CHECK that stock >= 0 on products and test it.
  2. Create courses and enrollments with a cascading foreign key and test a delete.
  3. Add a nullable phone column, then make it NOT NULL with a default.
  4. Find orphan rows after loading with FOREIGN_KEY_CHECKS = 0.

Conclusion

Constraints keep MySQL data correct: NOT NULL, UNIQUE, CHECK (8.0.16+), FOREIGN KEY with RESTRICT, CASCADE or SET NULL. Name them, use InnoDB, change structure with ALTER TABLE, and treat large alterations with online DDL.

Quick Summary: NOT NULL, UNIQUE, CHECK, FOREIGN KEY actions, ALTER TABLE, online DDL.

Get Newsletter

Subscibe to our newsletter and we will notify you about the newest updates on Edugators