The CHECK constraint in SQL is used to limit the values that can be inserted into a column. It ensures that data entered into the database meets specific conditions or requirements. This constraint can be applied on a column or even on multiple columns.
🎨 Pro Tip: Use the CHECK
constraint to enforce business rules directly within the database, ensuring the data is valid before insertion.
You can add a CHECK
constraint while creating a table to ensure that data entered into specific columns follows certain rules.
Example: Create an employees table where the age must be greater than or equal to 18:
CREATE TABLE employees ( emp_id INT PRIMARY KEY, name VARCHAR(100), age INT, salary DECIMAL(10, 2), CHECK (age >= 18) );
In this example, the CHECK
constraint ensures that only employees aged 18 or older can be inserted into the employees
table.
You can also add a CHECK
constraint to an existing table using the ALTER TABLE
statement.
Example: Add a CHECK
constraint to the employees table to ensure that the salary is greater than 0:
ALTER TABLE employees ADD CHECK (salary > 0);
This statement adds a check to ensure that the salary for every employee is positive. If someone tries to insert a negative salary, the database will reject the insert.
A CHECK
constraint can have multiple conditions, and all conditions must be satisfied for the insertion or update to be allowed.
Example: Ensure that the age is greater than 18 and salary is greater than 0 in the employees table:
CREATE TABLE employees ( emp_id INT PRIMARY KEY, name VARCHAR(100), age INT, salary DECIMAL(10, 2), CHECK (age >= 18 AND salary > 0) );
Here, both conditions must be true for an employee to be successfully added to the employees
table: the age
must be 18 or older, and the salary
must be positive.
🛠️ Interactive Task: Try creating a students
table where the grade must be between 1 and 100. Use a CHECK
constraint to enforce this rule.
If you no longer need a CHECK
constraint, you can remove it with the ALTER TABLE
statement.
Example: Remove the CHECK
constraint from the employees table:
ALTER TABLE employees DROP CONSTRAINT CHECK;
This will remove the CHECK
constraint, allowing the insertion of data that was previously restricted by the check.
CHECK
constraint ensures that only valid data can be inserted, preventing errors and inconsistencies.AND
or OR
to create more complex rules.CHECK
constraint does not support subqueries or referencing other tables.
🎯 Interactive Task: Experiment by adding a CHECK
constraint to an existing table. Try using logical operators to create your own validation rules (e.g., check for positive values, limit string length, etc.).
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!