CREATE INDEX 是用于创建索引的 DDL 命令。
CREATE INDEX 一直存在于 PostgreSQL 中。
用法
进度跟踪
从 PostgreSQL 12 开始,可以通过视图 pg_stat_progress_create_index 来跟踪索引的创建。
变更历史
- PostgreSQL 18
- 为 GIN 索引 添加了
CREATE INDEX CONCURRENTLY ...支持 (commit 8492feb9) - 如果
autovacuum设置为off,表统计信息将不会更新 (commit d611f8b1)
- 为 GIN 索引 添加了
- PostgreSQL 15
- 添加了
UNIQUE [ NULLS [ NOT ] DISTINCT ]语法 (提交 94aa7cc5)
- 添加了
- PostgreSQL 13
- PostgreSQL 12
- 可以使用
pg_stat_progress_create_index跟踪CREATE INDEX的进度 (commit ab0dfc96)
- 可以使用
- PostgreSQL 11
- 添加了通过
INCLUDE子句支持覆盖索引 (commit 8224de4f)
- 添加了通过
- PostgreSQL 9.5
- 添加了
IF NOT EXISTS语法 (commit 08309aaf)
- 添加了
- PostgreSQL 9.1
- 添加了
COLLATE选项 (commit 414c5a2e)
- 添加了
- PostgreSQL 8.3
- 添加了
ASC/DESC/NULLS FIRST/NULLS LAST(用于 B-tree 索引) 选项 (commit 44317582)
- 添加了
- PostgreSQL 8.2
- PostgreSQL 8.0
- 添加了
TABLESPACE选项 (commit 2467394e)
- 添加了
- PostgreSQL 7.2
- 添加了对部分索引的支持 (initial commit f31dc0ad)
- PostgreSQL 6.1
- 实现了正确的多列索引创建 (commit 65019fcf)
示例
CREATE INDEX 的基本用法示例
postgres=# CREATE INDEX ON foo (bar_id);
CREATE INDEX
postgres=# \d foo
Table "public.foo"
Column | Type | Collation | Nullable | Default
--------+---------+-----------+----------+---------
id | integer | | not null |
bar_id | integer | | not null |
Indexes:
"foo_pkey" PRIMARY KEY, btree (id)
"foo_bar_id_idx" btree (bar_id)
Foreign-key constraints:
"foo_bar_id_fkey" FOREIGN KEY (bar_id) REFERENCES bar(id)
参考资料
- PostgreSQL 文档: CREATE INDEX
有用链接
- 使用 Postgres CREATE INDEX:理解操作符类、索引类型等 - pganalyze 在 2021 年 8 月发布的博客文章
