解決對時間列運算導致不能走索引的問題

壹頁書發表於2014-04-14
劍破冰山Oracle開發藝術353頁

剛剛作為DBA入職新單位,檢視了一下AWR,發現很多SQL需要查詢當天的記錄。
模擬環境如下:

  1. create table test
  2. (
  3.     c1 timestamp
  4. );

  5. insert into test select systimestamp+(rownum-10) from dual connect by level<=20;

  6. commit;

  7. create index inx_test on test(c1);

SQL> select * from test;

C1
---------------------------------------------------------------------------
04-APR-14 11.35.43.000000 PM
05-APR-14 11.35.43.000000 PM
06-APR-14 11.35.43.000000 PM
07-APR-14 11.35.43.000000 PM
08-APR-14 11.35.43.000000 PM
09-APR-14 11.35.43.000000 PM
10-APR-14 11.35.43.000000 PM
11-APR-14 11.35.43.000000 PM
12-APR-14 11.35.43.000000 PM
13-APR-14 11.35.43.000000 PM
14-APR-14 11.35.43.000000 PM
15-APR-14 11.35.43.000000 PM
16-APR-14 11.35.43.000000 PM
17-APR-14 11.35.43.000000 PM
18-APR-14 11.35.43.000000 PM
19-APR-14 11.35.43.000000 PM
20-APR-14 11.35.43.000000 PM
21-APR-14 11.35.43.000000 PM
22-APR-14 11.35.43.000000 PM
23-APR-14 11.35.43.000000 PM

20 rows selected.


SQL> select systimestamp from dual;

SYSTIMESTAMP
---------------------------------------------------------------------------
14-APR-14 12.12.43.878915 AM +08:00

原來的SQL很多都是這樣寫的

SQL> select * from test where trunc(c1)=trunc(sysdate);

C1
---------------------------------------------------------------------------
14-APR-14 11.35.43.000000 PM

沒有建立函式索引的情況下,都是全表掃描的。
改寫問題SQL
select * from test
where c1 >= to_timestamp(trunc(sysdate,'dd'))
and c1
檢視執行計劃


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

相關文章