NULL與索引

jelephant發表於2013-12-17
JEL@JEL >create table t (x int,y int);

Table created.

JEL@JEL >create unique index i_t on t(x,y);

Index created.

JEL@JEL >insert into t values (1,1);

1 row created.
JEL@JEL >insert into t values (1,null);

1 row created.

JEL@JEL >insert into t values (null,1);

1 row created.

JEL@JEL >insert into t values (null,null);

1 row created.

JEL@JEL >insert into t values (null,1);
insert into t values (null,1)
*
ERROR at line 1:
ORA-00001: unique constraint (JEL.I_T) violated

JEL@JEL >insert into t values (null,null);

1 row created.

如上知,(null,1)與(null,1)是相同的,而(null,null)與(null,null)不同

JEL@JEL >set autotrace on
JEL@JEL >select * from t where x is null;

         X          Y
---------- ----------
                    1




Execution Plan
----------------------------------------------------------
Plan hash value: 1601196873

--------------------------------------------------------------------------
| Id  | Operation         | Name | Rows  | Bytes | Cost (%CPU)| Time     |
--------------------------------------------------------------------------
|   0 | SELECT STATEMENT  |      |     3 |     9 |    17   (0)| 00:00:01 |
|*  1 |  TABLE ACCESS FULL| T    |     3 |     9 |    17   (0)| 00:00:01 |
--------------------------------------------------------------------------

Predicate Information (identified by operation id):
---------------------------------------------------

   1 - filter("X" IS NULL)

如上計劃執行全表掃描


對列y加not null約束
JEL@JEL >truncate table t;

Table truncated.

JEL@JEL >alter table t modify y int not null;

Table altered.

JEL@JEL >insert into t values (1,1);

1 row created.

JEL@JEL >insert into t values (null,1);

1 row created.

JEL@JEL >exec dbms_stats.gather_table_stats('JEL','T');

PL/SQL procedure successfully completed.

JEL@JEL >set autotrace on
JEL@JEL >select * from t where x is null;

         X          Y
---------- ----------
                    1


Execution Plan
----------------------------------------------------------
Plan hash value: 2616361825

-------------------------------------------------------------------------
| Id  | Operation        | Name | Rows  | Bytes | Cost (%CPU)| Time     |
-------------------------------------------------------------------------
|   0 | SELECT STATEMENT |      |     1 |     5 |     1   (0)| 00:00:01 |
|*  1 |  INDEX RANGE SCAN| I_T  |     1 |     5 |     1   (0)| 00:00:01 |
-------------------------------------------------------------------------

Predicate Information (identified by operation id):
---------------------------------------------------

   1 - access("X" IS NULL)

如上走索引了


結論,對於複合索引,只有當索引鍵中至少一個列定義為not null時,查詢才會使用索引

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/29337971/viewspace-1063527/,如需轉載,請註明出處,否則將追究法律責任。

相關文章