Why isn't index used for this query?

后端 未结 4 2077
太阳男子
太阳男子 2021-02-05 18:05

I had a query where an index was not used when I thought it could be, so I reproduced it out of curiosity:

Create a test_table with 1.000.000 rows (10 disti

4条回答
  •  -上瘾入骨i
    2021-02-05 18:53

    you forgot this really important information: COL is not null

    If the column is NULLABLE, the index can not be used because there might be unindexed rows.

    SQL> ALTER TABLE test_table MODIFY (col NOT NULL);
    
    Table altered
    SQL> EXPLAIN PLAN FOR
      2  SELECT col, COUNT(*) FROM test_table GROUP BY col;
    
    Explained
    SQL> SELECT * FROM table(dbms_xplan.display);
    
    PLAN_TABLE_OUTPUT
    --------------------------------------------------------------------------------
    Plan hash value: 1077170955
    --------------------------------------------------------------------------------
    | Id  | Operation            | Name       | Rows  | Bytes | Cost (%CPU)| Time
    --------------------------------------------------------------------------------
    |   0 | SELECT STATEMENT     |            |    10 |    30 |  1954   (1)| 00:00:2
    |   1 |  SORT GROUP BY NOSORT|            |    10 |    30 |  1954   (1)| 00:00:2
    |   2 |   INDEX FULL SCAN    | TEST_INDEX |   976K|  2861K|  1954   (1)| 00:00:2
    --------------------------------------------------------------------------------
    

提交回复
热议问题