Postgresql 中文操作指南

11.6. Unique Indexes #

索引还可用于强制列值的唯一性或多个列的组合值的唯一性。

Indexes can also be used to enforce uniqueness of a column’s value, or the uniqueness of the combined values of more than one column.

CREATE UNIQUE INDEX name ON table (column [, ...]) [ NULLS [ NOT ] DISTINCT ];

目前,只有 B 树索引可声明为唯一。

Currently, only B-tree indexes can be declared unique.

当索引声明为唯一时,不允许具有相等索引值的多个表行。默认情况下,唯一列中的空值不被视为相等,允许列中有多个空值。NULLS NOT DISTINCT 选项会修改此项并使索引将空值视为相等。多列唯一索引将仅拒绝在多行中所有索引列都相等的情况。

When an index is declared unique, multiple table rows with equal indexed values are not allowed. By default, null values in a unique column are not considered equal, allowing multiple nulls in the column. The NULLS NOT DISTINCT option modifies this and causes the index to treat nulls as equal. A multicolumn unique index will only reject cases where all indexed columns are equal in multiple rows.

当对表定义唯一约束或主键时,PostgreSQL 会自动创建一个唯一索引。索引会涵盖构成主键或唯一约束的列(如果合适,则涵盖多列索引),它是强制执行约束的机制。

PostgreSQL automatically creates a unique index when a unique constraint or primary key is defined for a table. The index covers the columns that make up the primary key or unique constraint (a multicolumn index, if appropriate), and is the mechanism that enforces the constraint.

Note

无需手动创建唯一列的索引,这样只会复制自动创建的索引。

There’s no need to manually create indexes on unique columns; doing so would just duplicate the automatically-created index.