此脚本不依赖统计信息。

    有时开发人员可能会胡乱建立一些索引,但是这些索引在数据库中可能并不会被任何一个 SQL 使用。这样的索引会增加维护成本,我们可以将其删掉。下面脚本查询 SQL 使用哪些索引。

    1. select a.sql_text, a.sql_id, b.object_owner, b.object_name, b.object_type
    2. from v$sql a, v$sql_plan b
    3. where a.sql_id = b.sql_id
    4. and a.child_number = b.child_number
    5. and object_owner = 'SCOTT'
    6. and object_type like '%INDEX%'
    7. order by 3,4,5;

    我们在 Scott 账户中运行下面 SQL 并且查看执行计划。

    1. select * from t where object_id<100;
    1. 98 rows selected.
    2. Execution Plan
    3. ----------------------------------------------------------
    4. Plan hash value: 827754323
    5. -------------------------------------------------------------------------------------
    6. | Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
    7. -------------------------------------------------------------------------------------
    8. | 0 | SELECT STATEMENT | | 91 | 8827 | 4 (0)| 00:00:01 |
    9. | 1 | TABLE ACCESS BY INDEX ROWID| T | 91 | 8827 | 4 (0)| 00:00:01 |
    10. |* 2 | INDEX RANGE SCAN | IDX_ID | 91 | | 2 (0)| 00:00:01 |
    11. -------------------------------------------------------------------------------------
    12. Predicate Information (identified by operation id):
    13. ---------------------------------------------------
    14. 2 - access("OBJECT_ID"<100)

    我们通过脚本将它抓出。

    1. select a.sql_text, a.sql_id, b.object_owner, b.object_name, b.object_type
    2. from v$sql a, v$sql_plan b
    3. where a.sql_id = b.sql_id
    4. and a.child_number = b.child_number
    5. and object_owner = 'SCOTT'
    6. and object_type like '%INDEX%'
    7. order by 3,4,5;
    1. SQL_TEXT SQL_ID OBJECT_OWNER OBJECT_NAME OBJECT_TYPE
    2. -------------------------------- ------------ ------------ -------------- -----------
    3. select * from t where object_id<100 0nvp2p03p06k4 SCOTT IDX_ID INDEX