In this post explains how to use the check constraints in SQL Server (Transact-SQL) with syntax and examples.
A check constraint in SQL Server (Transact-SQL) allows you to specify a condition on each row in a table.
The syntax for creating a check constraint using a CREATE TABLE statement in SQL Server (Transact-SQL) is:
The name of the table that you wish to create with a check constraint.
The name to assign to the check constraint.
The column in the table that the check constraint applies to.
The condition that must be met for the check constraint to succeed.
Let's look at an example of how to use the CREATE TABLE statement in SQL Server to create a check constraint.
For example:
In this first example, we've created a check constraint on the employees table called check_employee_id. This constraint ensures that the employee_id field contains values between 1 and 10000.
Let's take a look at another example.
In this second example, we've created a check constraint on the employees table called check_salary. This constraint ensures that the salary value is greater than 0.
The syntax for creating a check constraint in an ALTER TABLE statement in SQL Server (Transact-SQL) is:
The name of the table that you wish to modify by adding a check constraint.
The name to assign to the check constraint.
The column in the table that the check constraint applies to.
The condition that must be met for the check constraint to succeed.
Let's look at an example of how to use the ALTER TABLE statement to create a check constraint in SQL Server.
For example:
In this example, we've created a check constraint on the existing employees table called check_last_name. It ensures that the last_name field only contains the following values: Smith, Mark, or Jones.
The syntax for dropping a check constraint in SQL Server (Transact-SQL) is:
The name of the table that you wish to drop the check constraint.
The name of the check constraint to remove.
Let's look at an example of how to drop a check constraint in SQL Server.
For example:
In this SQL Server example, we are dropping a check constraint on the employees table called check_last_name.
The syntax for enabling a check constraint in SQL Server (Transact-SQL) is:
The name of the table that you wish to enable the check constraint.
The name of the check constraint to enable.
Let's look at an example of how to enable a check constraint in SQL Server.
For example:
In this example, we are enabling a check constraint on the employees table called check_salary.
The syntax for disabling a check constraint in SQL Server (Transact-SQL) is:
The name of the table that you wish to disable the check constraint.
The name of the check constraint to disable.
Let's look at an example of how to disable a check constraint in SQL Server.
For example:
In this SQL Server example, we are disabling a check constraint on the employees table called check_salary.