SQL CHECK constraint

A CHECK constraint in SQL is used to limit the values that can be inserted into a column. It ensures that the data in a table satisfies a specific condition.

Why CHECK Constraint is Used
   • Ensures valid data
   • Prevents incorrect values
   • Enforces business rules

Example rules:
   • Age ≥ 18
   • Salary > 0
   • Quantity between 1 and 100

Basic Syntax

CREATE TABLE table_name (
    column_name datatype,
    CONSTRAINT constraint_name CHECK (condition)
);

Example (Orders Table)

CREATE TABLE Orders (
    order_id INT PRIMARY KEY,
    order_amount DECIMAL(10,2),
    quantity INT,
    CHECK (order_amount > 0),
    CHECK (quantity > 0)
);

Another Example (Age Check)

CREATE TABLE Customers (
    customer_id INT PRIMARY KEY,
    name VARCHAR(50),
    age INT CHECK (age >= 18)
);

Short definition:
A CHECK constraint ensures that values in a column satisfy a specified condition.


Topics