索引对单列最值查询的显著性影响(百万级别表单列最值查询 Cost由1405变成3)

表结构:

create table hy_emp(
    id number(7,0) primary key,
    name nvarchar2(20) not null,
    salary number(5,0) not null)

充值:

insert into hy_emp
select rownum,dbms_random.string('*',dbms_random.value(1,20)),dbms_random.value(1,99999)
from dual
connect by level<1000000

开始查看最值的解释计划:

EXPLAIN PLAN FOR
select max(salary) from hy_emp 

select * from table(dbms_xplan.display);

结果:

复制代码
Plan hash value: 2361586491
 
-----------------------------------------------------------------------------
| Id  | Operation          | Name   | Rows  | Bytes | Cost (%CPU)| Time     |
-----------------------------------------------------------------------------
|   0 | SELECT STATEMENT   |        |     1 |     5 |  1405   (1)| 00:00:01 |
|   1 |  SORT AGGREGATE    |        |     1 |     5 |            |          |
|   2 |   TABLE ACCESS FULL| HY_EMP |   999K|  4882K|  1405   (1)| 00:00:01 |
-----------------------------------------------------------------------------
复制代码

注意到因为operation是全表扫描,而cost是1405.

实际上我们需要的值少于整体的5%,又是查单列最值,因此在salary列上加上索引。

create index idx_emp_sal on hy_emp(salary);

再次查看解释计划:

EXPLAIN PLAN FOR
select max(salary) from hy_emp 

select * from table(dbms_xplan.display);

结果:

复制代码
Plan hash value: 876127496
 
------------------------------------------------------------------------------------------
| Id  | Operation                  | Name        | Rows  | Bytes | Cost (%CPU)| Time     |
------------------------------------------------------------------------------------------
|   0 | SELECT STATEMENT           |             |     1 |     5 |     3   (0)| 00:00:01 |
|   1 |  SORT AGGREGATE            |             |     1 |     5 |            |          |
|   2 |   INDEX FULL SCAN (MIN/MAX)| IDX_EMP_SAL |     1 |     5 |     3   (0)| 00:00:01 |
------------------------------------------------------------------------------------------
复制代码

相对上次有两点变化:一是operation变成索引全扫描,cost变成了3;二是Rows变成1,因为加了索引后DB只要查询B树的端点值就行了,一路向左就能找到。

从这两点看,单列最值加索引还是挺显著的。

--2020-04-03--

posted @   逆火狂飙  阅读(199)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)
历史上的今天:
2018-04-03 【高中数学/导数】已知f(x)=x^3-x+1,则以下选项正确的是()[多选](全国统考高考真题)
2018-04-03 【Python】http.client库的用法
生当作人杰 死亦为鬼雄 至今思项羽 不肯过江东
点击右上角即可分享
微信分享提示