The CHECK constraint in MySQL is used to ensure that values stored in a column satisfy a specific logical condition. It helps you enforce business rules directly at the database level so that invalid data is rejected automatically.
CHECK (...) must be true for every row.CHECK can apply to a single column or multiple columns together.A basic CHECK constraint on a single column can be defined while creating the table.
-- CHECK constraint on a single column
CREATE TABLE Employees (
ID INT,
Name VARCHAR(100),
Age INT CHECK (Age >= 18)
);
You can also combine multiple conditions using logical operators such as AND and OR.
In this example, the Age column must be between 18 and 65, and the Salary must always be a positive value.
-- Employees table with multiple CHECK constraints
CREATE TABLE Employees (
ID INT,
Name VARCHAR(100),
Age INT CHECK (Age >= 18 AND Age <= 65),
Salary DECIMAL(10,2) CHECK (Salary > 0)
);
When you try to insert a row, MySQL evaluates all CHECK constraints. If every condition is satisfied, the row is inserted; otherwise, the statement fails.
-- Valid insert: passes all CHECK constraints
INSERT INTO Employees (ID, Name, Age, Salary)
VALUES (1, 'Alice', 25, 50000.00);
-- Invalid insert: fails because Age < 18
INSERT INTO Employees (ID, Name, Age, Salary)
VALUES (2, 'Bob', 16, 40000.00);
INSERT, the values satisfy: Age >= 18 AND Age <= 65 and Salary > 0, so the row is inserted successfully.INSERT, Age = 16 violates the CHECK (Age >= 18 AND Age <= 65) rule, so MySQL rejects the row and returns an error.CHECK to enforce important business rules, such as: minimum age, valid score ranges, non-negative quantities, and positive prices.CHECK (Age >= 18 AND Age <= 65) or CHECK (Status IN ('ACTIVE','INACTIVE')).CHECK constraint, as it can affect existing data rules.Students table with a CHECK constraint that only allows marks between 0 and 100.CHECK constraint to a Products table to ensure that Quantity and Price are always positive.CHECK (Age >= 18 AND Country = 'India'), and test different INSERT statements.