表结构:
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 order by dbms_random.random;
开始查看最值的解释计划:
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--