MySQL Constraints: NOT NULL, UNIQUE, DEFAULT, CHECK
Constraints are rules the database enforces on every insert and update. They protect data quality far better than checks in application code, because they apply to every program, script and person that touches the table.
| Constraint | Rule |
|---|---|
NOT NULL |
the column must have a value |
UNIQUE |
no two rows may have the same value |
PRIMARY KEY |
NOT NULL + UNIQUE; identifies each row (next lesson) |
FOREIGN KEY |
the value must exist in another table (next lesson) |
CHECK |
a condition every row must satisfy |
DEFAULT |
not a rule but a value used when none is given |
Constraints are declared in CREATE TABLE, either on a column (email VARCHAR(80) UNIQUE) or as a separate table constraint, which can span several columns and carry a name (CONSTRAINT uq_name UNIQUE (first_name, last_name)).
NOT NULL
CREATE TABLE members (
member_id INT PRIMARY KEY,
name VARCHAR(50) NOT NULL,
nickname VARCHAR(20)
);
INSERT INTO members (member_id, name) VALUES (1, 'Ada');
SELECT * FROM members;
INSERT INTO members (member_id, name, nickname) VALUES (2, NULL, 'mystery');+-----------+------+----------+
| member_id | name | nickname |
+-----------+------+----------+
| 1 | Ada | NULL |
+-----------+------+----------+
ERROR 1048 (23000) at line 8: Column 'name' cannot be null
nickname is optional, name is not. An explicit NULL for a NOT NULL column is always an error. (If you simply omit a NOT NULL column without a default, strict mode, which is on by default, also refuses the row.)
UNIQUE
UNIQUE forbids duplicate values. NULLs are not considered equal to each other, so a unique column can hold any number of NULLs, like the three NULL e-mails in customers:
INSERT IGNORE INTO customers (first_name, last_name, email, country, signup_date)
VALUES ('Ana', 'Clone', 'ana.silva@example.com', 'Portugal', '2025-06-01'),
('Nina', 'Null', NULL, 'Spain', '2025-06-01');
SELECT ROW_COUNT() AS inserted;
SELECT COUNT(*) AS customers, COUNT(email) AS emails FROM customers;+----------+
| inserted |
+----------+
| 1 |
+----------+
+-----------+--------+
| customers | emails |
+-----------+--------+
| 16 | 12 |
+-----------+--------+
INSERT IGNORE skipped the duplicate e-mail and inserted the second row (a fourth NULL e-mail). A plain INSERT would have stopped with error 1062:
INSERT INTO customers (first_name, last_name, email, country, signup_date)
VALUES ('Ana', 'Clone', 'ana.silva@example.com', 'Portugal', '2025-06-01');
-- MySQL 8: ERROR 1062 (23000): Duplicate entry 'ana.silva@example.com' for key 'customers.email'
-- (MariaDB names the key just 'email')A unique constraint over several columns allows repeats in each column but not in the combination:
CREATE TABLE shifts (
employee_id INT,
work_day DATE,
CONSTRAINT uq_one_shift_per_day UNIQUE (employee_id, work_day)
);DEFAULT
DEFAULT gives a column a value when an INSERT doesn't mention it, or when it says DEFAULT explicitly. Since MySQL 8.0.13 a default can also be an expression in parentheses:
CREATE TABLE tickets (
ticket_id INT AUTO_INCREMENT PRIMARY KEY,
subject VARCHAR(60) NOT NULL,
priority VARCHAR(10) NOT NULL DEFAULT 'normal',
points INT DEFAULT (2 * 5),
opened_on DATE NOT NULL DEFAULT '2025-01-01'
);
INSERT INTO tickets (subject) VALUES ('Printer jam');
INSERT INTO tickets (subject, priority, points) VALUES ('Server down', 'urgent', DEFAULT);
SELECT * FROM tickets;+-----------+-------------+----------+--------+------------+
| ticket_id | subject | priority | points | opened_on |
+-----------+-------------+----------+--------+------------+
| 1 | Printer jam | normal | 10 | 2025-01-01 |
| 2 | Server down | urgent | 10 | 2025-01-01 |
+-----------+-------------+----------+--------+------------+
A common real-world default is the current time, created_at DATETIME DEFAULT CURRENT_TIMESTAMP. (We avoid printing it here, since it would change on every run.)
CHECK
A CHECK constraint holds a condition that every row must satisfy. MySQL enforces CHECK since 8.0.16; older versions parsed it and silently ignored it.
CREATE TABLE ratings (
product_id INT NOT NULL,
stars TINYINT NOT NULL,
CONSTRAINT chk_stars CHECK (stars BETWEEN 1 AND 5)
);
INSERT IGNORE INTO ratings VALUES (1, 5), (2, 9), (3, 1);
SELECT * FROM ratings;+------------+-------+
| product_id | stars |
+------------+-------+
| 1 | 5 |
| 3 | 1 |
+------------+-------+
The row with 9 stars broke the rule and was skipped by INSERT IGNORE. A plain INSERT fails, with a message that differs between the two servers:
INSERT INTO ratings VALUES (2, 9);
-- MySQL 8: ERROR 3819 (HY000): Check constraint 'chk_stars' is violated.
-- MariaDB: ERROR 4025 (23000): CONSTRAINT `chk_stars` failed for `shop`.`ratings`A check condition can compare columns of the same row, for example CHECK (shipped_date >= order_date), but it can't use subqueries or look at other rows or tables. Note also that a CHECK is satisfied when its condition is NULL, so CHECK (stars > 0) lets NULL through unless the column is NOT NULL.
Listing a table's constraints
SELECT CONSTRAINT_NAME, CONSTRAINT_TYPE
FROM information_schema.TABLE_CONSTRAINTS
WHERE TABLE_SCHEMA = 'shop' AND TABLE_NAME = 'customers'
ORDER BY CONSTRAINT_NAME;+-----------------+-----------------+
| CONSTRAINT_NAME | CONSTRAINT_TYPE |
+-----------------+-----------------+
| email | UNIQUE |
| PRIMARY | PRIMARY KEY |
+-----------------+-----------------+
A column-level UNIQUE gets the column's name (email) as its constraint name. Name your constraints yourself (CONSTRAINT uq_customer_email UNIQUE (email)) and they are easier to find and drop later.
Test yourself
How many NULLs can a UNIQUE column hold in MySQL?
- None
- One
- Any number
- Only if it is also the primary key
Since which MySQL version are CHECK constraints enforced?
- 5.0
- 5.7
- 8.0.16
- They never are
When is the DEFAULT value used?
- When the INSERT omits the column or writes DEFAULT
- When the value is invalid
- Whenever the value is 0
- On every UPDATE