SQL Check

www.igift‮.aedi‬com

In SQL, the CHECK constraint is used to specify a condition that must be true for each row in a table. The CHECK constraint ensures that the values in a column satisfy a specific condition or set of conditions.

Here is an example of how to create a CHECK constraint on a table:

CREATE TABLE employees (
    employee_id INT PRIMARY KEY,
    employee_name VARCHAR(50),
    salary DECIMAL(10,2),
    CONSTRAINT salary_check CHECK (salary >= 0)
);

In this example, the employees table has a CHECK constraint on the salary column. The salary column must be greater than or equal to zero for each row in the table.

You can also use the CHECK constraint to ensure that a column has a specific value or set of values. For example:

CREATE TABLE customers (
    customer_id INT PRIMARY KEY,
    customer_name VARCHAR(50),
    customer_type CHAR(1) DEFAULT 'R',
    CONSTRAINT customer_type_check CHECK (customer_type IN ('R', 'B'))
);

In this example, the customers table has a CHECK constraint on the customer_type column. The customer_type column can only have the values 'R' or 'B', which stand for residential and business customers, respectively.

You can add a CHECK constraint to an existing table using the ALTER TABLE command:

ALTER TABLE employees
ADD CONSTRAINT salary_check CHECK (salary >= 0);

In this example, we are adding a CHECK constraint to the salary column of the employees table using the ALTER TABLE command.

By using the CHECK constraint, you can help ensure that data is entered correctly and that specific conditions are met for each row in the table.