In SQL, the CHECK constraint is used to enforce a condition on the values that are inserted or updated in a column. It allows you to define a condition that must be satisfied for the values in a column to be considered valid. If a value violates the specified condition, the database will reject the insertion or update operation. Here's an example of how to use the CHECK constraint:
sql
CREATE TABLE table_name (
column_name data_type,
...
CONSTRAINT constraint_name CHECK (condition)
);
To add the CHECK constraint to an existing column using ALTER TABLE:
sql
ALTER TABLE table_name
ADD CONSTRAINT constraint_name CHECK (condition);
To drop the CHECK constraint from a column using ALTER TABLE:
sql
ALTER TABLE table_name
DROP CONSTRAINT constraint_name;
Replace `table_name` with the name of the table, `column_name` with the name of the column you want to apply or modify the CHECK constraint on, `constraint_name` with a name for the constraint (optional), and `condition` with the condition that must be satisfied.
sql
CREATE TABLE students (
id INT,
age INT,
gender VARCHAR(10),
CONSTRAINT chk_age CHECK (age >= 18),
CONSTRAINT chk_gender CHECK (gender IN ('Male', 'Female'))
);
In this example, two CHECK constraints are defined: `chk_age` ensures that the age must be 18 or greater, and `chk_gender` ensures that the gender can only be either "Male" or "Female".
The CHECK constraint allows you to enforce specific conditions on column values to ensure data integrity and consistency. It can be used to restrict the range of valid values or enforce specific patterns in the data.
Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.
We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc