PostgreSQL开发小讲堂 - 不等于、数组不包含 要不要用索引?

本文探讨了在PostgreSQL中如何处理不等于查询以利用索引,包括使用外连接、not exists和partial index的方法。文章通过实例展示了不同情况下的查询计划,并建议在大量数据情况下采用游标分页返回结果。此外,还涉及了数组查询中不包含操作的索引策略。
摘要由CSDN通过智能技术生成

标签

PostgreSQL , 不等于 , 索引 , 外连接


背景

在数据库中不等于能不能走索引呢?理论上是不行的,但是有方法可以让不等于也走索引(虽然走索引也不一定好)。

比如使用外连接实现(需要表有PK才行,没有PK可以使用行号代替),或者使用not exists,或者使用partial index(不支持变量)。

对于返回结果集很大的场景,建议使用游标分页返回,此时可能用全表扫描更适合。

例子1, 有PK

create table tbl_pk(id int primary key, c1 int);  
create index idx_tbl_pk on tbl_pk(c1);  
insert into tbl_pk select generate_series(1,1000000), random()*10000;  

原始方法,不能走索引
select * from tbl_pk where c1 <> 1;

postgres=# explain (analyze,verbose,timing,costs,buffers) select * from tbl_pk where c1 <> 1;

QUERY PLAN

Seq Scan on public.tbl_pk (cost=0.00..16925.00 rows=999902 width=8) (actual time=0.020..182.603 rows=999919 loops=1)
Output: id, c1
Filter: (tbl_pk.c1 <> 1)
Rows Removed by Filter: 81
Buffers: shared hit=4425
Planning time: 0.486 ms
Execution time: 249.335 ms
(7 rows)

让他走索引的写法

postgres=# explain (analyze,verbose,timing,costs,buffers) select t1.* from tbl_pk t1 left join tbl_pk t2 on (t1.id=t2.id and t2.c1=1) where t2.* is null;  
                                                            QUERY PLAN                                                               
-----------------------------------------------------------------------------------------------------------------------------------  
 Hash Left Join  (cost=352.55..18528.53 rows=5000 width=8) (actual time=0.229..395.158 rows=999919 loops=1)  
   Output: t1.id, t1.c1  
   Hash Cond: (t1.id = t2.id)  
   Filter: (t2.* IS NULL)  
   Rows Removed by Filter: 81  
   Buffers: shared hit=4509  
   ->  Seq Scan on public.tbl_pk t1  (cost=0.00..14425.00 rows=1000000 width=8) (actual time=0.009..128.644 rows=1000000 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值