我是新来的,想知道:

这已经是一个索引了吗?

ALTER TABLE workers_times ADD CONSTRAINT no_overlap_times EXCLUDE USING gist (user_id WITH =, available WITH &&)

我不想重叠时间,但我用GIST添加了一个约束.那么,这现在是一个索引吗,或者我仍然应该创建一个这样的索引

CREATE INDEX I_WORKERS_TIMES ON workers_times(user_id, available);

或者,上述指数不是必须的?

推荐答案

从它自动创建索引的意义上说,它是一个索引.严格来说,Constraints不一定要涉及一个指数,this one does:

排除约束是使用索引来实现的,因此每个指定的运算符必须与索引访问方法index_method的适当运算符类(参见第11.10节)相关联.

您的怀疑是正确的,因为unique(因此也是primary key)会自动创建索引并由索引强制执行,而创建唯一约束有时会换成只创建唯一索引,因为它们最终提供了相同的功能:

添加唯一约束将自动在约束中列出的列或列组上创建唯一B树索引.

请记住,所有这些都只是实现细节,无论多么不可能,它们都可能在future 发生变化


psql中,您可以运行\d+ workers_times元命令来查看表上的所有约束and索引,无论它们是单独创建的还是作为约束的一部分--此排除约束以索引demo的形式列出

create table workers_times(
    user_id uuid,
    available tstzrange);

create extension btree_gist;

ALTER TABLE workers_times 
  ADD CONSTRAINT no_overlap_times 
  EXCLUDE USING gist (user_id WITH =, available WITH &&);
\d+ workers_times
                                         Table "public.workers_times"
  Column   |   Type    | Collation | Nullable | Default | Storage  | Compression | Stats target | Description
-----------+-----------+-----------+----------+---------+----------+-------------+--------------+-------------
 user_id   | uuid      |           |          |         | plain    |             |              |
 available | tstzrange |           |          |         | extended |             |              |
Indexes:
    "no_overlap_times" EXCLUDE USING gist (user_id WITH =, available WITH &&)
Access method: heap

Here's a table显示了索引、约束、作为约束的索引和排除约束之间的区别:

control over index constraint index as constraint exclusion constraint
collation, direction, null order YES no no YES
custom equality no no no YES
include payload column YES YES YES YES
index storage parameters YES YES YES YES
tablespace YES YES YES YES
partial (WHERE) YES no no YES
multi-column YES YES YES YES
deferred validation no YES YES YES
nulls not distinct YES YES YES YES* (emulated by coalesce() or requires not distinct from operator)
creating concurrently YES no YES no (and no equivalent index syntax to enable adding as constraint)

Postgresql相关问答推荐

如何确定要与给定转储文件一起使用的pg_Restore版本?

在连接字符串并将其附加到 PostgreSQL 中的 where 子句时出现语法错误.怎么修?

JOOQ:数据库版本早于 COCKROACHDB 支持的方言:13.0.0

如何判断上次在 TimescaleDB 上运行连续聚合作业(job)的时间

PL/pgSQL 中 PL/SQL %ISOPEN 的类似功能是什么?

Postgres 14 反斜杠 Z 没有给出正确的输出

Postgres - 如何加入两列?

我可以在 Ruby on Rails 上编写 PostgreSQL 函数吗?

处理 sqlalchemy 断开连接的更好方法

OpenShift:如何从我的 PC 连接到 postgresql

Select 日期最高的行

Docker Compose + Spring Boot + Postgres 连接

为什么 PostgreSQL 数组访问在 C 中比在 PL/pgSQL 中快得多?

Postgres 日期重叠约束

为 postgresql 存储过程设置隔离级别

当成功有时会导致退出代码为 1 时,如何可靠地确定 pg_restore 是否成功?

在 PostgreSQL 中跳过每 n 个结果行

解释结果中的Recheck Cond是什么意思?

如何将 CSV 数据插入 PostgreSQL 数据库(远程数据库)

在 Postgres 9.0+ 中使用 PL/pgSQL 在表上循环