MySQL CHECK Constraint
MySQL CHECK Constraint
The CHECK constraint in MySQL is used to ensure that the values in a column meet a specific condition.
It is a way to enforce data integrity rules at the column or table level.
⚠️ MySQL supports
CHECKconstraints fully from version 8.0.16.
🔹 Syntax (Column-Level)
-
condition→ Logical expression that values must satisfy
🔹 Syntax (Table-Level)
-
Can reference one or more columns
🔹 Syntax (Using ALTER TABLE)
-
Adds a
CHECKconstraint to an existing table
🔹 Example 1: Column-Level CHECK
-
Ensures
marksare between 0 and 100
🔹 Example 2: Table-Level CHECK
-
Ensures
bonusis no more than 20% of salary
🔹 Example 3: Adding CHECK Using ALTER TABLE
-
Adds a named
CHECKconstraint to themarkscolumn after table creation
🔹 Key Points
-
CHECK enforces specific rules on column or table values.
-
Helps maintain valid and consistent data.
-
Can be applied during creation or added later using
ALTER TABLE. -
Multiple
CHECKconstraints can exist in a table. -
Useful for ranges, conditions, or logical rules on data.
