Skip to main content
The UNIQUE specifies that each non-NULL value in the constrained column must be unique.

Details

  • You can insert NULL values into columns with the UNIQUE constraint because NULL is the absence of a value, so it is never equal to other NULL values 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 is NULL. If you need to strictly enforce uniqueness, use the in addition to the UNIQUE constraint. You can also achieve the same behavior through the table’s .
  • Columns with the UNIQUE constraint automatically have an created with the name _<columns_key. To avoid having two identical indexes, you should not create indexes that exactly match the UNIQUE constraint’s columns and order. The UNIQUE constraint depends on the automatically created index, so dropping the index also drops the UNIQUE constraint. Conversely, also drops the automatically created index.
  • When using the UNIQUE constraint 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 the UNIQUE constraint to each column individually.
  • You can define the UNIQUE constraint when you create a table, or you can add it to an existing table through .
In , most users should use instead of explicit index . When you add an index to a REGIONAL BY ROW table, it is automatically partitioned on the . Explicit index partitioning is not required. While CockroachDB process an or statement on a particular database, creating or modifying an index will throw an error. Similarly, all and 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 .

Syntax

You can define UNIQUE constraints at the table level and at the column level.

Table level

unique_table_level syntax diagram
ParameterDescription
table_nameThe name of the table you are creating.
column_defDefinitions for any other columns in the table.
nameThe name you want to use for the constraint, which must be unique to its table and follow these .
column_nameThe name of the column you want to constrain.
table_constraintsAny other table-level you want to apply.
Example

Column level

unique_column_level syntax diagram
ParameterDescription
table_nameThe name of the table you are creating.
column_nameThe name of the constrained column.
column_typeThe constrained column’s .
column_constraintsAny other column-level you want to apply to this column.
column_defDefinitions for any other columns in the table.
table_constraintsAny table-level you want to apply.
Example

Usage example

As mentioned in the details above, it is possible when using the UNIQUE constraint alone to insert NULL values in a way that causes rows to appear to have rows with duplicate values.

See also