雖然索引並不總會快於全表掃描,可是不少時候咱們但願Oracle使用索引來執行某些SQL,這時候咱們能夠經過index hints來強制SQL使用index.數據庫
Index Hints的格式以下:ide
/*+ INDEX ( table [index [index]...] ) */
咱們簡單看一下這個提示的用法(範例爲Oracle10g數據庫):this
SQL> create table t as select username,password from dba_users;
Table created.
SQL> create index i_t on t(username);
Index created.
SQL> set autotrace trace explain
SQL> select /*+ index(t i_t) */ * from t where username='EYGLE';
Execution Plan ---------------------------------------------------------- Plan hash value: 2928007915
------------------------------------------------------------------------------------ | Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time | ------------------------------------------------------------------------------------ | 0 | SELECT STATEMENT | | 1 | 34 | 2 (0)| 00:00:01 | | 1 | TABLE ACCESS BY INDEX ROWID| T | 1 | 34 | 2 (0)| 00:00:01 | |* 2 | INDEX RANGE SCAN | I_T | 1 | | 1 (0)| 00:00:01 | ------------------------------------------------------------------------------------
Predicate Information (identified by operation id): ---------------------------------------------------
2 - access("USERNAME"='EYGLE')
Note ----- - dynamic sampling used for this statement
這裏的查詢使用了索引.spa
須要注意的是使用CTAS方式建立數據表,新建表會繼承原表的約束屬性:code
SQL> desc t Name Null? Type ----------------------------------------- -------- ---------------------------- USERNAME NOT NULL VARCHAR2(30) PASSWORD VARCHAR2(30)
若是不使用Hints,此處Oracle不會使用索引:orm
SQL> select * from t where username='EYGLE';
Execution Plan ---------------------------------------------------------- Plan hash value: 1601196873
-------------------------------------------------------------------------- | Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time | -------------------------------------------------------------------------- | 0 | SELECT STATEMENT | | 1 | 34 | 2 (0)| 00:00:01 | |* 1 | TABLE ACCESS FULL| T | 1 | 34 | 2 (0)| 00:00:01 | --------------------------------------------------------------------------
Predicate Information (identified by operation id): ---------------------------------------------------
1 - filter("USERNAME"='EYGLE')
Note ----- - dynamic sampling used for this statement
索引和全表掃描的選擇和取捨並不是簡單,本文不做進一步探討.繼承