![]() |
VOOZH | about |
The CHECK constraint in SQL ensures that only valid data enters a column by enforcing specific conditions. If a value doesnβt satisfy the defined rule, the insert or update operation is blocked.
Query:
-- Creating a table with a CHECK constraint
CREATE TABLE Staff (
StaffID INT PRIMARY KEY,
FullName VARCHAR(50),
Salary DECIMAL(10,2) CHECK (Salary > 0 AND Salary <= 50000)
);
-- This insert will succeed
INSERT INTO Staff (StaffID, FullName, Salary) VALUES
(1, 'Taylor Reed', 45000),
(2, 'John Doe', 42000);
Output:
Query:
INSERT INTO Staff (StaffID, FullName, Salary) VALUES
(3, 'Jordan Miles', -3000),
(4, 'Evan Clarke', 62000);
Error:
Syntax:
1. Using CHECK with CREATE TABLE:
CREATE TABLE table_name (
column1 datatype,
column2 datatype CHECK (condition),
...
);
2. Using CHECK with ALTER TABLE:
ALTER TABLE table_name
ADD CONSTRAINT constraint_name CHECK (condition);
Letβs look at some practical examples to better understand how the CHECK constraint works in SQL.
In this example, the Customers table restricts Age to 18 to 120, and the CHECK constraint blocks any value outside this range.
Query:
CREATE TABLE Customers (
CustomerID INT PRIMARY KEY,
Name VARCHAR(50),
Age INT CHECK (Age >= 18 AND Age <= 120)
);
-- Valid insert
INSERT INTO Customers (CustomerID, Name, Age)
VALUES (1, 'John Doe', 25);
-- Invalid insert
INSERT INTO Customers (CustomerID, Name, Age)
VALUES (2, 'Jane Smith', 15); -- This will fail due to the CHECK constraint
Output:
Error:
In this example, the CHECK constraint can also validate multiple columns, such as ensuring Salary is positive and Age is at least 18 in an Employee table.
Query:
CREATE TABLE Employee (
EmployeeID INT PRIMARY KEY,
Name VARCHAR(50),
Age INT,
Salary DECIMAL(10, 2),
CHECK (Age >= 18 AND Salary > 0)
);
-- Valid insert
INSERT INTO Employee (EmployeeID, Name, Age, Salary) VALUES
(1, 'Alice Johnson', 30, 50000),
(2, 'Bob Lee', 27, 47000);
-- Invalid insert (age < 18)
INSERT INTO Employee (EmployeeID, Name, Age, Salary)
VALUES (2, 'Bob Lee', 16, 45000); -- This will fail due to the CHECK constraint
Output:
Error:
We can add a CHECK constraint to an existing table using the ALTER TABLE statement.
Query:
ALTER TABLE Employee
ADD CONSTRAINT chk_salary CHECK (Salary >= 30000);