Check Constraints

Check constraints enforce domain integrity by limiting the values that are accepted by one or more columns. The search condition must evaluate to a Boolean expression and cannot contain subqueries. A column-level check constraint can reference only the constrained column, and a table-level check constraint can reference only columns of the constrained table.

Multiple check constraints can be defined for a table. SQL Server can define only one column-level check constraint per column per the CREATE TABLE statement (although each column constraint can have multiple conditions).

To Create a Check Constraint

Open the table you need, switch to the Constraints tab, and choose New Check Constraint on the shortcut menu.

To Edit a Check Constraint

Navigate to the constraint in Database Explorer and double-click it or open the table that owns the constraint, switch to the Constraints tab and choose Edit Constraint on the shortcut menu.

To Drop a Constraint

Navigate to the constraint in Database Explorer and choose Delete on the shortcut menu or open the table that owns the constraint, switch to the Constraints tab and choose Delete Constraint on its shortcut menu.

Example

Consider you need to ensure that all employees in table Emp have and will have salary that is more than 500. This can be implemented best with check constraint. Open the table and create the constraint as described above. In the Condition field, type Sal>500 and save the document. At this moment, all data in the table is checked for validity and, if it satisfies the condition, a new constraint is applied to the table.

This example assumes that you do not change some of constraint options which are located at the bottom of the constraint editor. These options add some flexibility to constraints during the creation and alteration. For example, you can:

  • Clear the Enabled option to prevent constraint from activating. You can enable it later.

  • Clear the Validate option to avoid verification of data that table already contains. Newly added or modified data still will be checked for validity.

  • Check the Deferrable option to preserve an opportunity of deferring check operation until a transaction is committed.