CHECK

SQL CHECK Constraint

CHECK limits the values a column can take, using any condition that refers to the row.

CREATE TABLE Persons (
    ID   INT PRIMARY KEY,
    Name VARCHAR(255) NOT NULL,
    Age  INT CHECK (Age >= 18)
);

Multi-column CHECK

Example

A named CHECK that compares two columns:

CREATE TABLE Discounts (
  ID INTEGER PRIMARY KEY,
  StartDate DATE,
  EndDate   DATE,
  Percent   INT,
  CONSTRAINT CK_Discount CHECK (EndDate > StartDate AND Percent BETWEEN 1 AND 90)
);
INSERT INTO Discounts VALUES (1, '2024-05-01', '2024-05-31', 15);
SELECT * FROM Discounts;

Result: 1 row

IDStartDateEndDatePercent
12024-05-012024-05-3115
INSERT INTO Discounts VALUES (2, '2024-06-10', '2024-06-01', 95);
-- Error: CHECK constraint failed: CK_Discount

Add / Drop CHECK

ALTER TABLE Products ADD CONSTRAINT CK_Price CHECK (Price >= 0);
ALTER TABLE Products DROP CONSTRAINT CK_Price;   -- MySQL 8.0.19+: DROP CHECK CK_Price

Note: MySQL ignored CHECK constraints before version 8.0.16. They were parsed but not enforced.