SQL CHECK Constraint
A SQL CHECK constraint is used to ensure that values in a column meet a specific condition or set of conditions. It helps enforce data integrity by restricting the range or type of data that can be entered into a table.
Syntax
CREATE TABLE table_name (
column_name data_type CHECK (condition)
);
Example
Let's create a table called Employees where we want to enforce that the salary of each employee must be greater than 0.
CREATE TABLE Employees (
EmployeeID INT PRIMARY KEY,
Name VARCHAR(50),
Salary DECIMAL(10, 2) CHECK (Salary > 0)
);
Explanation
EmployeeIDis the primary key.Nameis a column for the employee's name.Salaryis a column for the employee's salary, which must be greater than 0 due to theCHECKconstraint.
Inserting Data
If we try to insert valid and invalid data:
-- Valid insert
INSERT INTO Employees (EmployeeID, Name, Salary)
VALUES (1, 'John Doe', 50000.00);
-- Invalid insert (will fail)
INSERT INTO Employees (EmployeeID, Name, Salary)
VALUES (2, 'Jane Smith', -3000.00);
Output
For the valid insert, the data is added to the table:
| EmployeeID | Name | Salary |
|---|---|---|
| 1 | John Doe | 50000.00 |
For the invalid insert, you will receive an error message like:
ERROR: CHECK constraint failed: Employees
This error indicates that the Salary value does not satisfy the CHECK constraint condition.
Written by Shaikh Abdul Shahid
A Full-Stack Developer with experience in PHP, Laravel, JavaScript, and React.
Founder of Online Learner, sharing practical knowledge and programming tutorials.
Building and maintaining real-world web applications since 2017.
Your Feedback
Help us improve by sharing your thoughts
Online Learner helps developers master programming, database concepts, interview preparation, and real-world implementation through structured learning paths.
Quick Links
© 2023 - 2026 OnlineLearner.in | All Rights Reserved.
