字段中有null值查询不走索引的问题解决

生产环境发现有一条sql 效率很差,发现是由于查询中有null值,导致了执行计划不走索引。

搜索了解决办法,主要是创建该字段和其它常量字段的联合索引

或者通过函数索引排除空值的情况。


下面是测试过程

--测试


构造测试表
create table test_null
(id  number(10),
comm varchar2(20));

插入测试数据
declare
  i number;
begin
  for i in 1..100000 loop
   if mod(i,10) !=0 then 
     insert into test_null values (i,'aaa');
   else
     insert into test_null values (null,'aaa');
   end if;
   end loop;
   commit;
end;


创建索引
create index idx_test_null on test_null(id);

查询空值
select count(*) from test_null where id is null;   --全表扫描 


修改方案一
create index idx_test_null_1 on test_null(id,1);  
查询空值
select count(*) from test_null where id is null;   --走索引idx_test_null_1 range scan 

drop index idx_test_null_1;


修改方案二:
create index idx_test_null_2 on test_null(decode(id,null,1));
查询空值
select count(*) from test_null where (decode(id,null,1)=1);  --走索引idx_test_null_2 range scan  


drop index idx_test_null_2;



结果,两种方式都可以达到查询null值走索引的效果,但是由于创建函数索引还需要修改查询语句,代价较高,

故第一种修改方式比较好,直接创建该字段和一个常量的联合索引即可,

评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值