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

标签 postgresql database-design indexing unique-constraint unique-index

在阅读了 docs on index uniqueness being an implementation detail 之后,我一直在尝试理清 Postgres 中 unique 和索引之间的关系。 :

The preferred way to add a unique constraint to a table is ALTER TABLE ... ADD CONSTRAINT. The use of indexes to enforce unique constraints could be considered an implementation detail that should not be accessed directly. One should, however, be aware that there's no need to manually create indexes on unique columns; doing so would just duplicate the automatically-created index.

所以按照文档的说法,我将只声明事物是唯一的并使用隐式索引 - 或者 - 创建一个索引而不假设值是唯一的。这是一个错误吗?

我将从 unique 获得什么样的索引?鉴于只有 btree 会接受唯一约束并且 unique 隐式创建索引 UNIQUE 创建 btree 索引是真的吗?我不想无意中在哈希索引上运行范围。

最佳答案

create an index and not assume that the values are unique

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

定义一个 UNIQUE 约束与创建一个没有指定索引类型的唯一索引效果相同(几乎,见下文)。而且,我 quote the manual :

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

添加约束只是规范的方式,在未来的版本中不会破坏它可以以不同的方式实现。就这样。

不,unique constraint 只能在所有版本中使用基本的 btree 索引来实现,包括 PostgreSQL v14。引用段落 “ADD table_constraint_using_index” in the manual :

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命令并点击链接获取更多信息。

相关:

关于postgresql - PostgreSQL 如何强制执行 UNIQUE 约束/它使用什么类型的索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9066972/

相关文章:

Mysql避免冗余外键

python - 如何有效地为python数据帧中的每一行乘以特定值

postgresql - Postgres HashAggregate 运行缓慢

postgresql.conf max_prepared_transactions 不起作用

postgresql - 如何删除 Azure 中 Microsoft.DBforPostgreSQL/flexibleServers 的服务关联链接

mysql - 如何为这个 MySql 查询设置正确的索引?

python - 使用python的位置索引

php - 在 php7-fpm Docker 容器中安装 Postgres 驱动程序

MySQL 使用索引构建/链接表

database - 获取所有帖子的列表,其中包含用户喜欢的帖子以及Firestore中每个帖子的总喜欢数