postgresql - 我应该同时指定 INDEX 和 UNIQUE INDEX 吗?

标签 postgresql indexing unique-constraint unique-index

在我的一个 PostgreSQL 表上,我有一组两个字段,它们将被定义为在表中是唯一的,但在选择数据时也会一起使用。鉴于此,我只需要定义一个 UNIQUE INDEX,还是我应该在 UNIQUE INDEX 之外指定一个 INDEX?

这个?

CREATE UNIQUE INDEX mytable_col1_col2_idx ON mytable (col1, col2);

还是这个?

CREATE UNIQUE INDEX mytable_col1_col2_uidx ON mytable (col1, col2);
CREATE INDEX mytable_col1_col2_idx ON mytable (col1, col2);

最佳答案

如果您有 UNIQUE INDEX,那么您就不需要 INDEX - 它会是多余的。 UNIQUE INDEX 既是唯一约束,也是可以像任何其他索引一样使用的索引。

来自documentation :

Note: 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.

强调我的。

关于postgresql - 我应该同时指定 INDEX 和 UNIQUE INDEX 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4531693/

相关文章:

postgresql - 在现有的 Postgresql 数据库上连接 Neo4J

sql - 如何在 Postgres 中执行 SQL 查询而不显示结果

MongoDB 查询具有不存在的字段和索引的记录

python - 从列表或元组中显式选择项目

MySQL 查询优化快把我逼疯了!几乎一样,但又截然不同

java - JPA-存储库保存 : Proceed saving after insert Constraint violation

Postgresql 函数无法按预期使用 INSERT INTO

java - 相同的字段名称导致系统错误

sql - 获取具有条件的关联记录数

swift - 如何防止对多关系 NSManagedObject 在覆盖合并时与 CoreData 中的 Swift 重复?