MySQL Constraints
MySQL Constraints: Enforcing Data Integrity at the Schema Layer
MySQL constraints are rules attached to table columns that reject invalid inserts and updates before bad data enters your database. Enforcing constraints inside MySQL protects your data even when multiple microservices, background workers, or manual scripts write to the same tables.
Core Constraint Types in MySQL
| Constraint | Rule Enforced | Example Use Case |
|---|---|---|
NOT NULL |
Disallows NULL values |
Required email, price, status |
UNIQUE |
Prevents duplicate non-NULL values |
Unique email or product sku |
PRIMARY KEY |
Uniquely identifies every row (NOT NULL + UNIQUE) |
id column |
FOREIGN KEY |
Links child rows to an existing parent key | demo_orders.customer_id -> demo_customers.id |
CHECK |
Validates a custom boolean expression (MySQL 8.0.16+) | CHECK (price >= 0) |
DEFAULT |
Supplies a fallback value when omitted on INSERT |
DEFAULT 'pending' |
Practical SQL Example
This table definition combines all six core constraints inside demo_orders so bad prices, duplicate order codes, and orphan customer links are rejected immediately:
CREATE TABLE demo_orders (
id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
order_code VARCHAR(20) NOT NULL UNIQUE,
customer_id BIGINT UNSIGNED NOT NULL,
status VARCHAR(20) NOT NULL DEFAULT 'pending',
total_amount DECIMAL(10, 2) NOT NULL,
CONSTRAINT chk_demo_orders_total CHECK (total_amount >= 0),
CONSTRAINT fk_demo_orders_cust
FOREIGN KEY (customer_id) REFERENCES demo_customers(id)
);
Common Mistakes and Best Practices
- Name Your Constraints Explicitly: Using
CONSTRAINT chk_demo_orders_totalinstead of anonymous constraints makes error messages and futureALTER TABLE ... DROP CONSTRAINTmigrations effortless to manage across environments. - Do Not Rely Only on Frontend or ORM Validation: Application validation can be bypassed by concurrent race conditions, bulk CSV imports, or direct admin scripts. Database constraints act as your final, reliable source of truth.
- Clean Up Existing Data Before Adding Rules: MySQL rejects
ALTER TABLE ... ADD CONSTRAINTif any existing row violates the new constraint, so audit and fix stale rows first.
Frequently Asked Questions
Can I add constraints after a table already has data?
Yes, with ALTER TABLE, provided every existing row already satisfies the new rule (otherwise MySQL rejects the migration).
Which MySQL version added real CHECK constraint enforcement?
MySQL 8.0.16 added full CHECK constraint enforcement; older 5.7 and early 8.0 releases parsed CHECK syntax but silently ignored it.
How do I see all constraints defined on a table?
Run SHOW CREATE TABLE demo_orders; or query information_schema.TABLE_CONSTRAINTS.
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.