Constraints in MySQL are used to specify rules for data in a table. They are used to ensure the integrity of data in the database. Constraints enforce the accuracy and reliability of the data in a table.
Constraints can be defined during table creation or added later. They are enforced automatically by MySQL before data is inserted or updated.
-- Creating a users table with multiple constraints
CREATE TABLE users (
id INT AUTO_INCREMENT,
username VARCHAR(50) NOT NULL,
email VARCHAR(100) UNIQUE,
password VARCHAR(255) NOT NULL,
PRIMARY KEY (id),
CHECK (LENGTH(password) > 6)
);
This table ensures unique users, non-empty values, and validates password length automatically.
-- Linking orders table with users table using foreign key
CREATE TABLE orders (
order_id INT AUTO_INCREMENT,
user_id INT,
order_date DATE,
PRIMARY KEY (order_id),
FOREIGN KEY (user_id) REFERENCES users(id)
);
The foreign key ensures every order is linked to a valid user, maintaining referential integrity.
users.id ➜ orders.user_id
This relationship visually represents how foreign keys connect tables.