Skip to main content
The PRIMARY KEY constraint specifies that the constrained columns’ values must uniquely identify each row. A table can only have one primary key, but it can have multiple unique constraints. You should explicitly define a table’s primary key in the CREATE TABLE statement. If you don’t define a primary key at table creation time, CockroachDB will create a rowid column that is NOT VISIBLE, use the unique_rowid() function as its default value, and use that as the table’s primary key. You can change the primary key of an existing table with an ALTER TABLE ... ALTER PRIMARY KEY statement, or by using DROP CONSTRAINT and then ADD CONSTRAINT in the same transaction. You cannot fully drop the PRIMARY KEY constraint on a table without replacing it as it provides an intrinsic structure to the table’s data.

Syntax

PRIMARY KEY constraints can be defined at the table level. However, if you only want the constraint to apply to a single column, it can be applied at the column level.

Column level

primary_key_column_level syntax diagram Example

Table level

primary_key_table_level syntax diagram Example

Details

The columns in the PRIMARY KEY constraint are used to create its primary index, which CockroachDB uses by default to access the table’s data. This index does not take up additional disk space (unlike secondary indexes, which do) because CockroachDB uses the primary index to structure the table’s data in the key-value layer. For more information, see our blog post SQL in CockroachDB: Mapping Table Data to Key-Value Storage. To ensure each row has a unique identifier, the PRIMARY KEY constraint combines the properties of both the UNIQUE and NOT NULL constraints. The properties of both constraints are necessary to make sure each row’s primary key columns contain distinct sets of values. The properties of the UNIQUE constraint ensure that each value is distinct from all other values. However, because NULL values never equal other NULL values, the UNIQUE constraint is not enough (two rows can appear the same if one of the values is NULL). To prevent the appearance of duplicated values, the PRIMARY KEY constraint also enforces the properties of the NOT NULL constraint. For best practices, see Unique ID best practices. We strongly recommend adding size limits to all indexed columns, which includes columns in primary keys. Values exceeding 1 MiB can lead to storage layer write amplification and cause significant performance degradation or even crashes due to OOMs (out of memory errors). To add a size limit using CREATE TABLE:
To add a size limit using ALTER TABLE ... ALTER COLUMN:

Example

Changing primary key columns

You can change the primary key of an existing table by doing one of the following:
You can use an ADD CONSTRAINT ... PRIMARY KEY statement without a DROP CONSTRAINT ... PRIMARY KEY if the primary key was not explicitly defined at table creation, and the current primary key is on rowid.

See also