zoukankan      html  css  js  c++  java
  • 索引对单列极值查询的显著性影响(百万级别表单列最值查询 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
    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--

  • 相关阅读:
    DM8168 新三板系统启动
    AndroidAndroid程序提示和消息button响应事件
    Linux核心regulator建筑和准备
    对话(VC_Win32)
    VOJ 1067 Warcraft III 守望者的烦恼 (矩阵高速功率+dp)
    有所述网络流的上限和下限
    Matlab Newton‘s method
    Cocos2d-Java安装和配置跨平台游戏引擎以及相关的开发工具
    n每个计数的概率和发生骰子--动态规划
    自己写CPU第九阶段(3)——加载存储指令说明2(swl、swr)
  • 原文地址:https://www.cnblogs.com/heyang78/p/12624544.html
Copyright © 2011-2022 走看看