PostgreSQL的索引

PostgreSQL的索引

一、創(chuàng)建索引
create index 索引名 on 表名 [using method](列名1,列名2,..);



二、刪除索引
drop index [concurrently] [if exists] 索引名 [cascade | restrict];

參數(shù)解釋:
concurrently
在表上刪除索引的同時不對查詢,插入,更新,刪除加鎖。 普通的 DROP INDEX 會使表獲得獨(dú)占鎖,阻塞其他的訪問,直到
索引刪除完成。使用此選項(xiàng), 會由阻塞變?yōu)榈却?,直到其他沖突事物結(jié)束。

cascade
級聯(lián)刪除依賴于該索引的對象。

restrict
如果有依賴對象存在,則拒絕刪除該索引。這個是缺省。




三、列出索引:
select * from pg_indexes;
截圖


命令行:
\d table_name;
pg_indexes.png

四、索引類型:
B-tree索引:
查詢列使用到如下表達(dá)式時,一般使用B-tree索引:{默認(rèn)索引均為B-tree索引}
    <
    <=
    =
    >=
    between
    in
    is null
    is not null

    支持如下的模式匹配:
    column_name like 'foo%'
    column_name like 'bar%'
    column_name like ~ '^foo'


hash index:
當(dāng)查詢列只需使用表達(dá)式:=  一般使用hash index

gin index:

brin index:

gist index:

sp-gist indexes:




五、唯一索引:
指定唯一性后,索引的列的值必須唯一。如兩列或多列時,兩列或多列的值共同唯一。
create unique index 索引名 on 表名 (列名1,列名2...);




六、基于表達(dá)式的索引:
create index 索引名 on 表名 (表達(dá)式);

create index inx_title on film (lower(title));




七、局部索引:
create index 索引名 on 表名 (列名) where condition;

create index inx_title on film (title) where title like 'Cu%';



八、重新索引:
reindex {index | table | schema | database | system} name;

reindex index index_name;

reindex table table_name;

reindex schema schema_name;

reindex database database_name;

reindex system database_name;




九、多列索引:
create index 索引名 on 表名(a,b,c...);

where a=v1 and b=v2 and c=v3; 可以命中索引
where a=v1 and v=v2;          可以命中索引
where a=v1;                   可以命中索引
where c=v3 and b=v2;          有時可以命令有時不能命名索引,視具體環(huán)境
where a=v1 or b=v2;           不能命中索引


索引失效的場景:
1、任何計算、函數(shù)、類型轉(zhuǎn)換
2、!=
3、NOT,相當(dāng)于使用函數(shù)
4、模糊查詢通配符在開頭
5、索引字段在表中占比較高
6、多字段btree索引查詢條件不包含第一列
7、多字段索引查詢條件使用OR(有時也會走索引掃描,但查詢效率不高)
8、如果查詢的目標(biāo)表中數(shù)據(jù)量很少的情況下,PostgreSQL不會走索引查詢的,而是直接順序查找。
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容