postgresql会自动生成索引吗?

use*_*945 4 postgresql

Postgresql中有自动索引还是需要用户显式创建索引?如果有自动索引,如何查看?谢谢。

Sam*_*Sam 6

主键和唯一约束的索引将自动生成。使用CREATE INDEX,使更多的索引。要查看包含索引的现有数据库结构,请使用\d table

一个生成索引的简单示例是:

CREATE INDEX unique_index_name ON table (column);
Run Code Online (Sandbox Code Playgroud)

您可以在多个列上创建索引:

CREATE INDEX unique_index_name ON table (column1, column2, column3);
Run Code Online (Sandbox Code Playgroud)

或仅在满足条件时才存在的部分索引:

CREATE INDEX unique_index_name ON table (column) WHERE column > 0;
Run Code Online (Sandbox Code Playgroud)

您可以使用它们做更多的事情,但这是用于文档(上面链接)告诉您的。另外,如果您在生产数据库上创建索引,请使用CREATE INDEX CONCURRENTLY(这将花费更长的时间,但不会锁定对表的新写操作)。如果您还有其他问题,请告诉我。


更新:

如果要使用纯SQL查看索引,请查看下pg_catalog.pg_indexes表:

SELECT *
FROM pg_catalog.pg_indexes
WHERE schemaname='public'
AND tablename='table';
Run Code Online (Sandbox Code Playgroud)