Defining a Check Constraint Expression

See Also

When you attach a check constraint to a table or column, you must include an SQL expression. For details about this operation, see Attaching a New Check Constraint to a Table or Column.

You can create a simple constraint expression to check data for a simple condition; or you can create a complex expression, using Boolean operators, to check data for several conditions. For example, suppose the authors table has a zip column where a 5-digit character string is required. This sample constraint expression guarantees that only 5-digit numbers are allowed:

zip LIKE '[0-9][0-9][0-9][0-9][0-9]'

Or suppose the sales table has a column called qty which requires a value greater than 0. This sample constraint guarantees that only positive values are allowed:

qty > 0

Or suppose the orders table limits the type of credit cards accepted for all credit card orders. This sample constraint guarantees that if the order is placed on a credit card, then only Visa, MasterCard, or American Express is accepted:

NOT (payment_method = ‘credit card’) OR
   (card_type IN (‘VISA’, ‘MASTERCARD’, ‘AMERICAN EXPRESS’))

Note   Some databases have different functionality for check constraints. For more information about the differences between databases, see Database Server Considerations. Consult your database documentation for details about how your database works with check constraints.

To define a constraint expression

The SQL syntax is made up of the following parameters:

Parameter Description
constant A literal value, such as numeric or character data. Character data must be enclosed within single quotation marks (').
column_name Specifies a column.
function A built-in function. For details about functions, see "Functions" in SQL Server Books Online or Transact-SQL Reference.
operator An arithmetic, bitwise, comparison, or string operator. For details about operators, see "Operators" in SQL Server Books Online or Transact-SQL Reference.
AND Use in Boolean expressions to connect two expressions. Results are returned when both expressions are true.

When AND and OR are both used in a statement, AND is processed first. You can change the order of execution by using parentheses.

OR Use in Boolean expressions to connect two or more conditions. Results are returned when either condition is true.

When AND and OR are both used in a statement, OR is evaluated after AND. You can change the order of execution by using parentheses.

NOT Negates any Boolean expression (which can include keywords, such as LIKE, NULL, BETWEEN, IN, and EXISTS).

When more than one logical operator is used in a statement, NOT is processed first. You can change the order of execution by using parentheses.