The CHECK keyword in SQL is used to define a constraint that limits the values that can be inserted into a column. It ensures that the values in a column meet a specified condition. If the condition is not met, an error is raised, and the operation is rejected.
Syntax:
CREATE TABLE table_name (
column_name data_type,
CONSTRAINT constraint_name CHECK (condition)
);
Example:
-
Creating a table with a CHECK constraint:
CREATE TABLE employees ( id INT, name VARCHAR(100), age INT, CONSTRAINT chk_age CHECK (age >= 18) );In this example, the
CHECKconstraint ensures that only values whereageis greater than or equal to 18 can be inserted into theagecolumn. -
Using
CHECKwith a column definition:CREATE TABLE students ( id INT, name VARCHAR(100), grade CHAR(1), CHECK (grade IN ('A', 'B', 'C', 'D', 'F')) );In this example, the
CHECKconstraint ensures that thegradecolumn only contains values from the set('A', 'B', 'C', 'D', 'F'). -
Adding a
CHECKconstraint to an existing table:ALTER TABLE employees ADD CONSTRAINT chk_age CHECK (age >= 18);
Key Points:
- The condition inside the
CHECKconstraint can reference multiple columns and use operators like=,>,<,BETWEEN,IN, etc. - It can also be used to ensure that values fall within a certain range or match specific patterns (e.g., an email address).
- If a value violating the
CHECKconstraint is inserted, an error is thrown, and the insertion is blocked.
Note: Not all database systems support CHECK constraints, or they might implement them with slight variations.
No comments:
Post a Comment