How To Use Check In Sql in SQL
How to Use CHECK Constraint in SQL
The CHECK constraint is used to limit the values that can be placed in a column. It ensures that all values in a column satisfy a specific condition.
Syntax:
CREATE TABLE table_name ( column_name datatype CHECK (condition), ...);Or add a check constraint to an existing table:
ALTER TABLE table_nameADD CONSTRAINT constraint_name CHECK (condition);Example 1: Create Table with CHECK
CREATE TABLE employees ( employee_id INT PRIMARY KEY, age INT CHECK (age >= 18), -- age must be 18 or older salary DECIMAL(10, 2) CHECK (salary > 0) -- salary must be positive);Example 2: Add CHECK Constraint to Existing Table
ALTER TABLE employeesADD CONSTRAINT chk_salary_positive CHECK (salary > 0);Notes:
The
CHECKcondition can use comparison operators (=, <, >, <=, >=, <>), logical operators (AND, OR, NOT), and more.When you try to insert or update a value violating the check, the database throws an error.
Not all database engines enforce
CHECKconstraints strictly (e.g., older MySQL versions ignore them).
If you want, I can help you write a CHECK constraint for your specific table!