CHECK specifies that values for the column in or statements must return TRUE or NULL for a Boolean expression. If any values return FALSE, the entire statement is rejected.
Details
-
You can specify
CHECKconstraints at the column or table level and can reference other columns within the table. Internally, all column-levelCHECKconstraints are converted to table-level constraints so they can be handled consistently. -
You can add
CHECKconstraints to columns that were created earlier in the same transaction. For an example, see . -
You can have multiple
CHECKconstraints on a single column but for performance optimization you should combine them using logical operators. For example, you should specify:as: -
When you drop a column with a
CHECKconstraint, theCHECKconstraint is also dropped.
Syntax
You can defineCHECK constraints at the column level, where the constraint applies only to a single column, and at the table level.
You can also add CHECK constraints to a table using .
Column level
| Parameter | Description |
|---|---|
table_name | The name of the table you’re creating. |
column_name | The name of the constrained column. |
column_type | The constrained column’s . |
check_expr | An expression that returns a Boolean value; if the expression evaluates to FALSE, the value cannot be inserted. |
column_constraints | Any other column-level you want to apply to this column. |
column_def | Definitions for any other columns in the table. |
table_constraints | Any table-level you want to apply. |
Example
The following example specifies the column-levelCHECK constraint that a quantity_on_hand value must be greater than 0.
Table level
| Parameter | Description |
|---|---|
table_name | The name of the table you’re creating. |
column_def | Definitions for any other columns in the table. |
constraint_name | The name to use for the constraint, which must be unique to its table and follow these . |
check_expr | An expression that returns a Boolean value. If the expression evaluates to FALSE, the value cannot be inserted. |
table_constraints | Any other table-level to apply. |
Example
The following example specifies the table-levelCHECK constraint named ok_to_supply that a quantity_on_hand value must be greater than 0 and a warehouse_id must be between 100 and 200.
Usage example
The following example demonstrates that when you specify theCHECK constraint that a quantity_on_hand value must be greater than 0, and you attempt to insert the value 0, CockroachDB returns an error.

