[Oracle][Postgresql][mysql]三个数据库产品下表字段存在空值或者为空创建索引是否生效测试

本文通过测试Oracle 11.2、PostgreSQL 10.11和MySQL的索引行为,探讨了在表字段存在空值或空字符串时,创建的索引是否在查询中生效。测试结果显示,MySQL和PostgreSQL在使用等于空字符串或IS NULL条件时可能走索引,而Oracle则不会。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/*  ******************* postgresql 数据库测试开始   ***********************/
 

--本次测试以pg 数据库 10.11版本

postgres=# select version();
                           version
-------------------------------------------------------------
 PostgreSQL 10.11, compiled by Visual C++ build 1800, 64-bit
(1 行记录)


--创建一张测试表

create table t_index_null(id varchar(50),name text);

--造测试数据

insert into t_index_null(id,name)
select t.id,'test'||t.id::varchar
  from (select generate_series as id
          from generate_series(1,100000) ) as t;

--添加一条 id为null的数据  

insert into t_index_null(name) values ('zqw01');

--添加一条 id为空字符的数据  

insert into t_index_null(id,name) values ('','zqw02');

--对 id列 创建索引

create index idx_t_index_null_id on t_index_null(id);


--检锁id=1 的数据,看执行计划是否会走索引,走执行计划

explain analyze 
select id,name
  from t_index_null 
 where id = '1';

                                                            QUERY PLAN
-------------------------------------------------------------------------------------------
 Index Scan using idx_t_index_null_id on t_index_null  (cost=0.29..8.31 rows=1 width=14) (actual time=0.061..0.062 rows=1 loops=1)
   Index Cond: ((id)::text = '1'::text)
 Planning time: 0.289 ms
 Execution time: 0.086 ms
(4 行记录)

 
--检锁id='' (空字符) 的数据,看执行计划是否会走索引,走执行计划

explain analyze 
select id,name
  from t_index_null 
 where id = '';

                                                             QUERY PLAN
-------------------------------------------------------------------------------------------
 Index Scan using idx_t_index_null_id on t_index_null  (cost=0.29..8.31 rows=1 width=14) (actual time=0.050..0.052 rows=1 loops=1)
   Index Cond: ((id)::text = ''::text)
 Planning time: 0.114 ms
 Execution time: 0.078 ms
(4 行记录)


--检锁id is null (空字符) 的数据,看执行计划是否会走索引,走执行计划

explain analyze 
select id,name
  from t_index_null 
 where id is null;

 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值