oracle 主键_【oracle实验】--测试主键字段类型对执行计划的影响

概述

一般我们主键类型都为数字的,但是还是有些奇葩系统设计主键字段类型为varchar,下面看看这两个类型对执行计划的影响。


1、准备测试数据

grant select on dba_objects to scott;conn scott/tiger;create table t1 as select * from dba_objects where 1=0;alter table t1 add id int primary key;create table t2 as select * from dba_objects where 1=0;alter table t2 add id varchar2(10) primary key;
b629b1aec14de32e9957084a04899e5a.png

--插入300万数据

insert into t1 select 'test','test','test',rownum,rownum,'test',sysdate,sysdate,'test','t','t','t','t',rownum,'test',rownum from dual connect by rownum<=3000000;insert into t2 select 'test','test','test',rownum,rownum,'test',sysdate,sysdate,'test','t','t','t','t',rownum,'test',rownum from dual connect by rownum<=3000000;commit;
31a26bccc95d3b4d196067da519cb060.png

2、收集统计信息

execute dbms_stats.gather_table_stats(ownname=>'SCOTT',tabname=>'T1',cascade=>true,estimate_percent=>100);

execute dbms_stats.gather_table_stats(ownname=>'SCOTT',tabname=>'T2',cascade=>true,estimate_percent=>100);

e7eed3adf70a3c8cdf5cd5df5fe30f40.png

3、查看执行计划

conn / as sysdbaalter system flush shared_pool;conn scott/tiger;set autotrace traceonly;set line 1000;select * from t1 where id>=2999990;select * from t2 where id>='2999990';
574341769a33bcf52531191cb23bdab8.png

t1

对于普通的采用数值类型的字段,范围查询就是正常的索引范围扫描,执行效率很高。

beac840dc7e16c460693ce17d0d293b4.png

对于文本类型字段的表,范围查询就是对应的全扫,效率比较低。


4、结论

1、字符类型在索引中是乱序的,字符类型的排序方式与我们的预期不同,注意select * from t2 where id>='2999990'执行返回777788行,不是10条记录,这是表设计时需要注意的。

2、字符类型还导致了聚簇因子很大,原因是插入顺序与排序顺序不同,其实就是按照数字类型插入(1...3000000),按字符类型('1'....'3000000')t排序

3、在对字符类型使用大于运算符时,会导致优化器认为需要扫描索引大部分数据且聚簇因子很大,最终选择全表扫描方式。

ps:解决办法

 select * from t2 where id between '2999990' and '3000000';
70ee570b004ec4bdf4f6055a1e172e0c.png

这里将sql语句由开发区间扫描(>=)修改为封闭区间(between xx and max_value),使得数据在索引局部顺序是"对的"。如果这样还是走全扫,可以进一步细化分段或者采用逐条提取+批绑定的方法。


上面演示的是不好的数据类型导致执行计划异常的实验,可以看出数据结构设计是很重要的,建议在设计初期引入数据库审核,可以避免很多问题。

后面会分享更多DBA方面内容,感兴趣的朋友可以关注下!

cccdf27b4308e57c5a863a541ed15703.gif
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值