Check Constraint In Sql in SQL
? CHECK Constraint in SQL
The CHECK constraint is used to limit the values that can be placed in a column by specifying a Boolean expression. If the expression evaluates to FALSE or UNKNOWN, the data modification (INSERT or UPDATE) is rejected.
? Syntax
1. Adding CHECK constraint when creating a table
CREATE TABLE table_name ( column_name datatype, ..., CONSTRAINT constraint_name CHECK (condition));2. Adding CHECK constraint to an existing table
ALTER TABLE table_nameADD CONSTRAINT constraint_name CHECK (condition);? Examples
1. Creating a table with CHECK constraint
CREATE TABLE employees ( emp_id INT PRIMARY KEY, emp_name VARCHAR(100), age INT, CONSTRAINT chk_age CHECK (age >= 18 AND age <= 65));Ensures
ageis between 18 and 65.
2. Adding CHECK constraint to existing table
ALTER TABLE employeesADD CONSTRAINT chk_salary CHECK (salary > 0);Ensures
salaryis always positive.
? Key Points
CHECK constraints enforce data integrity at the column or table level.
Supported in most SQL databases like MySQL (since 8.0.16), PostgreSQL, SQL Server, Oracle.
The condition must be a Boolean expression.
If violated, the operation fails with an error.
Want examples with multiple columns or removing CHECK constraints?