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

xiaoxiao2021-02-27  142

生产环境发现有一条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值走索引的效果,但是由于创建函数索引还需要修改查询语句,代价较高,

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

转载请注明原文地址: https://www.6miu.com/read-14985.html

最新回复(0)