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__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. In multi-region deployments, most users should useREGIONAL BY ROWtables instead of explicit index partitioning. When you add an index to aREGIONAL BY ROWtable, it is automatically partitioned on thecrdb_regioncolumn. Explicit index partitioning is not required. While CockroachDB process anADD REGIONorDROP REGIONstatement on a particular database, creating or modifying an index will throw an error. Similarly, allADD REGIONandDROP REGIONstatements will be blocked while an index is being modified on aREGIONAL BY ROWtable within the same database. For an example that uses unique indexes, see Add a unique index to aREGIONAL BY ROWtable.
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.

