In SQL Server you can create a CHECK
constraint in a table to specify the data values that are acceptable in one or more columns.
If a table has a CHECK
constraint on it, and you try to provide data that doesn’t conform to the CHECK
constraint, the operation will fail with an error.
This helps to maintain data integrity, because it helps to prevent invalid data from entering the database.
When you create a CHECK
constraint, you provide a logical expression that returns TRUE
or FALSE
. This logical expression is what’s used to check the data.
CHECK
constraints are similar to foreign key constraints because they control the values that are put in a column. However, the difference is in how they determine which values are valid: Foreign key constraints obtain the list of valid values from another table, while CHECK
constraints determine the valid values from a logical expression.
Constraints can be defined at the column level or table level. A column-level constraint applies to just the data in that column. A table-level constraint applies to the whole row, and checks data from multiple columns.
Below are examples of creating both column-level and table-level CHECK
constraints.