Advertisement
Google Ad Slot: content-top
MySQL CHECK
MySQL CHECK Constraint
The CHECK constraint in MySQL is used to enforce rules on the values in a column. It ensures that the data entered into a table meets specific conditions.
Key Characteristics of CHECK Constraint
- Ensures data validity by applying conditions to columns.
- Applied during table creation or using
ALTER TABLE. - If the data doesn't meet the condition, MySQL throws an error.
- Can be used on one or multiple columns.
- Supports logical conditions using operators (
>,<,=,AND,OR, etc.).
Syntax for CHECK Constraint
CREATE TABLE table_name ( column1 data_type, column2 data_type, CONSTRAINT constraint_name CHECK (condition) );
CHECK on CREATE TABLE
Explanation:
agemust be 18 or older.scoremust be within the range of 0 to 100.- If values do not meet these criteria, MySQL will return an error.
To allow naming of a CHECK constraint, and for defining a CHECK constraint on multiple columns, use the following SQL syntax:
Explanation:
chk_age_score → Ensures that:
- Age is 18 or above.
- Score is 50 or above.
CHECK on ALTER TABLE
Explanation:
- A new constraint
chk_ageensures that the student's age is 18 or above.
DROP a CHECK Constraint
To drop a CHECK constraint, use the following SQL: