且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

PostgreSQL 如何强制执行 UNIQUE 约束/它使用什么类型的索引?

更新时间:2023-12-01 14:38:40

或者 - 创建一个索引并且不假设值是唯一的

or - create an index and not assume that the values are unique

如果您定义了唯一索引,则可以安全地假设值是唯一的.这就是唯一约束的实现方式(目前,并且可能在所有未来版本中也是如此).

It is safe to assume that values are unique, if you have a unique index defined. That's how unique constraints are implemented (at the time being, and probably in all future versions as well).

定义 UNIQUE 约束与创建唯一索引而不指定索引类型有效地相同(几乎见下文).而且,我引用手册:

Defining a UNIQUE constraint does effectively the same (almost, see below) as creating a unique index without specifying the index type. And, I quote the manual:

选择是 btree、hash、gist 和 gin.默认方法是btree.

Choices are btree, hash, gist, and gin. The default method is btree.

添加约束只是规范的方式,在未来的版本中不会中断,可以以不同的方式实现.仅此而已.

Adding a constraint is just the canonical way that would not break in future versions where it could be implemented differently. That's all.

不,唯一约束只能通过基本的btree索引在所有版本中实现,包括 PostgreSQL v14.我引用了ADD table_constraint_using_index"手册中的段落这里:

And no, a unique constraint can only be implemented with a basic btree index in all versions up to and including PostgreSQL v14. I quote the "ADD table_constraint_using_index" paragraph in the manual here:

索引不能有表达式列,也不能是部分索引.还,它必须是具有默认排序顺序的 b 树索引.

The index cannot have expression columns nor be a partial index. Also, it must be a b-tree index with default sort ordering.

###其他差异

  • 独特的约束可以推迟.这对于唯一索引是不可能的.看看SET CONSTRAINTS 命令并点击链接了解更多信息.
  • Unique constraints can be deferred. That is not possible for unique indexes. Have a look at the SET CONSTRAINTS command and follow the links for more.

外键必须引用作为主键或形成唯一约束.罢工>

A foreign key must reference columns that either are a primary key or form a unique constraint.

最后一点似乎已经过时或从一开始就存在误解.见:

The last bit seems to be outdated or a misunderstanding from the getgo. See:

相关: