postgresql 索引——迹忆客-ag捕鱼王app官网
索引是加速搜索引擎检索数据的一种特殊表查询。简单地说,索引是一个指向表中数据的指针。一个数据库中的索引与一本书的索引目录是非常相似的。
拿汉语字典的目录页(索引)打比方,我们可以按拼音、笔画、偏旁部首等排序的目录(索引)快速查找到需要的字。
索引有助于加快 select 查询和 where 子句,但它会减慢使用 update 和 insert 语句时的数据输入。索引可以创建或删除,但不会影响数据。
使用 create index 语句创建索引,它允许命名索引,指定表及要索引的一列或多列,并指示索引是升序排列还是降序排列。
索引也可以是唯一的,与 unique 约束类似,在列上或列组合上防止重复条目。
create index 命令
create index (创建索引)的语法如下:
create index index_name on table_name;
索引类型
单列索引
单列索引是一个只基于表的一个列上创建的索引,基本语法如下:
create index index_name
on table_name (column_name);
组合索引
组合索引是基于表的多列上创建的索引,基本语法如下:
create index index_name
on table_name (column1_name, column2_name);
不管是单列索引还是组合索引,该索引必须是在 whehe 子句的过滤条件中使用非常频繁的列。
如果只有一列被使用到,就选择单列索引,如果有多列就使用组合索引。
唯一索引
使用唯一索引不仅是为了性能,同时也为了数据的完整性。唯一索引不允许任何重复的值插入到表中。基本语法如下:
create unique index index_name
on table_name (column_name);
局部索引
局部索引 是在表的子集上构建的索引;子集由一个条件表达式上定义。索引只包含满足条件的行。基础语法如下:
create index index_name
on table_name (conditional_expression);
隐式索引
隐式索引 是在创建对象时,由数据库服务器自动创建的索引。索引自动创建为主键约束和唯一约束。
示例
下面实例将在 company 表的 salary 列上创建索引:
jiyik_db=# create index salary_index on company (salary);
现在,用 \d company 命令列出 company 表的所有索引:
jiyik_db=# \d company
得到的结果如下,company_pkey 是隐式索引 ,是表创建表时创建的:
table "public.company"
column | type | collation | nullable | default
--------- --------------- ----------- ---------- ---------
id | integer | | not null |
name | text | | not null |
age | integer | | not null |
address | character(50) | | |
salary | real | | |
indexes:
"company_pkey" primary key, btree (id)
"salary_index" btree (salary)
你可以使用 \di 命令列出数据库中所有索引:
jiyik_db=# \di
结果如下
list of relations
schema | name | type | owner | table
-------- ----------------- ------- ---------- ------------
public | company_pkey | index | postgres | company
public | department_pkey | index | postgres | department
public | salary_index | index | postgres | company
(3 rows)
drop index (删除索引)
一个索引可以使用 postgresql 的 drop 命令删除。
drop index index_name;
您可以使用下面的语句来删除之前创建的索引:
jiyik_db=# drop index salary_index;
删除后,可以看到 salary_index 已经在索引的列表中被删除:
jiyik_db=# \di
结果如下
list of relations
schema | name | type | owner | table
-------- ----------------- ------- ---------- ------------
public | company_pkey | index | postgres | company
public | department_pkey | index | postgres | department
(2 rows)
什么情况下要避免使用索引?
虽然索引的目的在于提高数据库的性能,但这里有几个情况需要避免使用索引。
使用索引时,需要考虑下列准则:
- 索引不应该使用在较小的表上。
- 索引不应该使用在有频繁的大批量的更新或插入操作的表上。
- 索引不应该使用在含有大量的 null 值的列上。
- 索引不应该使用在频繁操作的列上。