UNIQUE constraint specifies that each non-NULL value in the constrained column must be unique.
Details
-
You can insert
NULLvalues into columns with theUNIQUEconstraint becauseNULLis the absence of a value, so it is never equal to otherNULLvalues and not considered a duplicate value. This means that it’s possible to insert rows that appear to be duplicates if one of the values isNULL. If you need to strictly enforce uniqueness, use theNOT NULLconstraint in addition to theUNIQUEconstraint. You can also achieve the same behavior through the table’s Primary Key. -
Columns with the
UNIQUEconstraint automatically have an index created with the name_<columns_key. To avoid having two identical indexes, you should not create indexes that exactly match theUNIQUEconstraint’s columns and order. TheUNIQUEconstraint depends on the automatically created index, so dropping the index also drops theUNIQUEconstraint. Conversely, dropping theUNIQUEconstraint also drops the automatically created index. -
When using the
UNIQUEconstraint on multiple columns, the collective values of the columns must be unique. This does not mean that each value in each column must be unique, as if you had applied theUNIQUEconstraint to each column individually. -
You can define the
UNIQUEconstraint when you create a table, or you can add it to an existing table throughADD CONSTRAINT.
REGIONAL BY ROW tables instead of explicit index partitioning. When you add an index to a REGIONAL BY ROW table, it is automatically partitioned on the crdb_region column. Explicit index partitioning is not required.
While CockroachDB process an ADD REGION or DROP REGION statement on a particular database, creating or modifying an index will throw an error. Similarly, all ADD REGION and DROP REGION statements will be blocked while an index is being modified on a REGIONAL BY ROW table within the same database.
For an example that uses unique indexes, see Add a unique index to a REGIONAL BY ROW table.
Syntax
You can defineUNIQUE constraints at the table level and at the column level.
Table level
Example
Column level
Example
Usage example
UNIQUE constraint alone to insert NULL values in a way that causes rows to appear to have rows with duplicate values.

