一些性能不佳的查询涉及"IS NULL"条件,类似于:
bash
SQL>UPDATE T1 SET id2 = 1 WHERE id2 IS NULL;
Execution Plan
----------------------------------------------------------
Plan hash value: 2927627013
---------------------------------------------------------------------------
| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
---------------------------------------------------------------------------
| 0 | UPDATE STATEMENT | | 4 | 52 | 80 (2)| 00:00:01 |
| 1 | UPDATE | T1 | | | | |
|* 2 | TABLE ACCESS FULL| T1 | 4 | 52 | 80 (2)| 00:00:01 |
Oracle 不会在索引中存储 NULL 值,因此即使 T1.ID2 列上确实存在索引,它也无法使用。
有一个有用的索引技巧可以帮助调整这个语句。 创建一个索引并将常量值添加到索引末尾,以便存储 NULL 值。
bash
SQL> create index idx_id2 on t1(id2,1)
SQL> UPDATE T1 SET id2 = 1 WHERE id2 IS NULL;
99999 rows updated.
Execution Plan
----------------------------------------------------------
Plan hash value: 4068505729
-----------------------------------------------------------------------------
| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
-----------------------------------------------------------------------------
| 0 | UPDATE STATEMENT | | 4 | 52 | 33 (0)| 00:00:01 |
| 1 | UPDATE | T1 | | | | |
|* 2 | INDEX RANGE SCAN| IDX_ID2 | 4 | 52 | 33 (0)| 00:00:01 |
-----------------------------------------------------------------------------
这一次,sql选择走index,并且cost更低