SQL Server Interview Question #38
What is a CHECK constraint?
Data Types, Keys & Constraints Junior Beginner
Detailed Explanation
A CHECK constraint validates data according to a Boolean condition before SQL Server accepts an INSERT or UPDATE.
It is useful for enforcing domain rules close to the data, such as preventing negative prices, restricting percentages to a valid range, or validating allowed numeric ranges.
Application validation is still useful for user experience, but database CHECK constraints protect the rule regardless of which application writes to the database.
Code Example
CREATE TABLE Products
(
Id INT IDENTITY PRIMARY KEY,
Name NVARCHAR(200) NOT NULL,
Price DECIMAL(18,2) NOT NULL,
Rating DECIMAL(2,1) NULL,
CONSTRAINT CK_Products_Price
CHECK (Price >= 0),
CONSTRAINT CK_Products_Rating
CHECK (Rating IS NULL OR Rating BETWEEN 0 AND 5)
);