SQL
Enforce Data Validation with a CHECK Constraint
Add a CHECK constraint to a SQL table column to automatically enforce specific data validation rules, ensuring data integrity and preventing invalid entries.
ALTER TABLE Employees
ADD CONSTRAINT CK_EmployeeSalary_Valid CHECK (Salary >= 0 AND Salary <= 1000000);
-- To add a named constraint during table creation:
-- CREATE TABLE Products (
-- ProductID INT PRIMARY KEY,
-- ProductName VARCHAR(255) NOT NULL,
-- Price DECIMAL(10, 2) CHECK (Price > 0)
-- );
How it works: This snippet demonstrates how to add a CHECK constraint to an existing table's column. A CHECK constraint is a powerful SQL feature that enforces data integrity by ensuring that all values in a column meet specified criteria (e.g., Salary must be non-negative and within a maximum limit). This prevents invalid data from being inserted or updated, maintaining the quality and reliability of your database.