> ## Documentation Index
> Fetch the complete documentation index at: https://docs.cockroachlabs.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Primary Key Constraint

The `PRIMARY KEY` [constraint](/docs/stable/constraints.md) 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](/docs/stable/unique.md).

You should explicitly define a table's primary key in the [`CREATE TABLE`](/docs/stable/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](/docs/stable/functions-and-operators#id-generation-functions) as its default value, and use that as the table's primary key.

You can [change the primary key](#changing-primary-key-columns) of an existing table with an [`ALTER TABLE ... ALTER PRIMARY KEY`](/docs/stable/alter-table#alter-primary-key) statement, or by using [`DROP CONSTRAINT`](/docs/stable/alter-table#drop-constraint) and then [`ADD CONSTRAINT`](/docs/stable/alter-table#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](#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).

### Column level

![primary\_key\_column\_level syntax diagram](https://mintcdn.com/cockroachlabs/UZNSFbmU2EwEm6G5/images/sql-diagrams/common/primary_key_column_level.svg?fit=max\&auto=format\&n=UZNSFbmU2EwEm6G5\&q=85\&s=d4009a935f047a88b571315ce03a05ca)

| Parameter | Description |
| - | - |
| `table_name` | The name of the table you're creating. |
| `column_name` | The name of the Primary Key column. For [multi-region tables](/docs/stable/multiregion-overview.md#table-locality), you can use the `crdb_region` column within a composite primary key in the event the original primary key may contain non-unique entries across multiple, unique regions. |
| `column_type` | The Primary Key column's [data type](/docs/stable/data-types.md). |
| `column_constraints` | Any other column-level [constraints](/docs/stable/constraints.md) you want to apply to this column. |
| `column_def` | Definitions for any other columns in the table. |
| `table_constraints` | Any table-level [constraints](/docs/stable/constraints.md) you want to apply. |

**Example**

```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
> CREATE TABLE orders (
    order_id        UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    order_date      TIMESTAMP NOT NULL,
    order_mode      STRING(8),
    customer_id     INT,
    order_status    INT
  );
```

### Table level

![primary\_key\_table\_level syntax diagram](https://mintcdn.com/cockroachlabs/UZNSFbmU2EwEm6G5/images/sql-diagrams/common/primary_key_table_level.svg?fit=max\&auto=format\&n=UZNSFbmU2EwEm6G5\&q=85\&s=0a8e420a956943bdaa1bb0fdcc4a7b2a)

| Parameter | Description |
| - | - |
| `table_name` | The name of the table you're creating. |
| `column_def` | Definitions for any other columns in the table. |
| `name` | The name you want to use for the constraint, which must be unique to its table and follow these [identifier rules](/docs/stable/keywords-and-identifiers.md#identifiers). |
| `column_name` | The name of the column you want to use as the `PRIMARY KEY`. The order in which you list columns here affects the structure of the primary index. |
| `table_constraints` | Any other table-level [constraints](/docs/stable/constraints.md) you want to apply. |

**Example**

```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
> CREATE TABLE IF NOT EXISTS inventories (
    product_id        INT,
    warehouse_id      INT,
    quantity_on_hand  INT NOT NULL,
    PRIMARY KEY (product_id, warehouse_id)
  );
```

## Details

The columns in the `PRIMARY KEY` constraint are used to create its primary [index](/docs/stable/indexes.md#creation), 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](https://www.cockroachlabs.com/blog/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`](/docs/stable/unique) and [`NOT NULL`](/docs/stable/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](/docs/stable/performance-best-practices-overview.md#unique-id-best-practices).

We **strongly recommend** adding size limits to all [indexed columns](/docs/stable/indexes.md), which includes columns in [primary keys](/docs/stable/primary-key.md).

Values exceeding 1 MiB can lead to [storage layer write amplification](/docs/stable/architecture/storage-layer.md#write-amplification) and cause significant performance degradation or even [crashes due to OOMs (out of memory errors)](/docs/stable/cluster-setup-troubleshooting.md#out-of-memory-oom-crash).

To add a size limit using [`CREATE TABLE`](/docs/stable/create-table):

```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
CREATE TABLE name (first STRING(100), last STRING(100));
```

To add a size limit using [`ALTER TABLE ... ALTER COLUMN`](/docs/stable/alter-table#alter-column):

```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
ALTER TABLE name ALTER first TYPE STRING(99);
```

## Example

```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
> CREATE TABLE IF NOT EXISTS inventories (
    product_id        INT,
    warehouse_id      INT,
    quantity_on_hand  INT NOT NULL,
    PRIMARY KEY (product_id, warehouse_id)
  );
```

```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
> INSERT INTO inventories VALUES (1, 1, 100);
```

```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
> INSERT INTO inventories VALUES (1, 1, 200);
```

```
pq: duplicate key value (product_id,warehouse_id)=(1,1) violates unique constraint "primary"
```

```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
> INSERT INTO inventories VALUES (1, NULL, 100);
```

```
pq: null value in column "warehouse_id" violates not-null constraint
```

## Changing primary key columns

You can change the primary key of an existing table by doing one of the following:

* Issuing an [`ALTER TABLE ... ALTER PRIMARY KEY`](/docs/stable/alter-table#alter-primary-key) statement. When you change a primary key with `ALTER PRIMARY KEY`, the old primary key index becomes a secondary index. This helps optimize the performance of queries that still filter on the old primary key column.
* Issuing an [`ALTER TABLE ... DROP CONSTRAINT ... PRIMARY KEY`](/docs/stable/alter-table#drop-constraint) statement to drop the primary key, followed by an [`ALTER TABLE ... ADD CONSTRAINT ... PRIMARY KEY`](/docs/stable/alter-table#add-constraint) statement, in the same transaction, to add a new primary key. This replaces the existing primary key without creating a secondary index from the old primary key. For examples, see [Add constraints](/docs/stable/alter-table.md#add-constraints) and [Drop constraints](/docs/stable/alter-table.md#drop-constraints).

> [!NOTE]
>
> You can use an [`ADD CONSTRAINT ... PRIMARY KEY`](/docs/stable/alter-table#add-constraint) statement without a [`DROP CONSTRAINT ... PRIMARY KEY`](/docs/stable/alter-table#drop-constraint) if the primary key was not explicitly defined at [table creation](/docs/stable/create-table.md), and the current [primary key is on `rowid`](/docs/stable/indexes#creation).

## See also

* [Constraints](/docs/stable/constraints.md)
* [`CHECK` constraint](/docs/stable/check)
* [`DEFAULT` constraint](/docs/stable/default-value)
* [`REFERENCES` constraint (Foreign Key)](/docs/stable/foreign-key)
* [`PRIMARY KEY` constraint](/docs/stable/primary-key)
* [`NOT NULL` constraint](/docs/stable/not-null)
* [`UNIQUE` constraint](/docs/stable/unique)
* [`SHOW CONSTRAINTS`](/docs/stable/show-constraints)
* [`ALTER PRIMARY KEY`](/docs/stable/alter-table#alter-primary-key)
* [`ALTER TABLE`](/docs/stable/alter-table)
