Oracle timestamp類型是否可以直接和日期類型比較大小
前言
一般時間戳的字段比較范圍用time >= to_timestamp來。
今天發現一條SQL,發現時間戳類型的字段使用了CAST作類型轉換為DATE類型,然后在去和DATE類型做比較。
這樣做導致了無法使用該字段上的索引,后來建議直接去掉函數處理部分。
改為:
以前處理故障用到gv$active_session_history.sample_time或者dba_hist_active_sess_history.sample_time倒是直接是類似如下使用,
select .... from gv$active_session_history where sample_time >=to_date('2021-01-05 08:00:00','yyyy-mm-dd hh24:mi:ss')
and sample_time <=to_date('2021-01-05 08:05:00','yyyy-mm-dd hh24:mi:ss');
也是可以使用的。這里還是做個試驗看看。
環境構造
22:16:54 ZKM@test(1028)> create table aa as select sample_time from gv$active_session_history; Table created. Elapsed: 00:00:00.29 22:17:00 ZKM@test(1028)> desc aa; Name Null? Type ----------------------------------------- -------- ---------------------------- SAMPLE_TIME TIMESTAMP(3) 22:17:11 ZKM@test(1028)> alter session set nls_timestamp_format='yyyy-mm-dd hh24:mi:ss.ff9'; Session altered. Elapsed: 00:00:00.01 22:17:15 ZKM@test(1028)> col MIN(SAMPLE_TIME) for a30 22:17:19 ZKM@test(1028)> col MAX(SAMPLE_TIME) for a30 22:17:19 ZKM@test(1028)> set line 500 22:17:19 ZKM@test(1028)> select min(sample_time),max(sample_time) from aa; MIN(SAMPLE_TIME) MAX(SAMPLE_TIME) ------------------------------ ------------------------------ 2021-01-05 08:29:45.993000000 2021-01-05 22:16:58.509000000 Elapsed: 00:00:00.52 22:26:24 ZKM@test(1028)> alter session set nls_timestamp_format='yyyy-mm-dd hh24:mi:ss.ff'; Session altered. Elapsed: 00:00:00.00 22:26:43 ZKM@test(1028)> select min(sample_time),max(sample_time) from aa; MIN(SAMPLE_TIME) MAX(SAMPLE_TIME) ------------------------------ ------------------------------ 2021-01-05 08:29:45.993 2021-01-05 22:16:58.509 Elapsed: 00:00:00.01
試驗過程
比如查找aa表中時間小於等於"2021-01-05 08:29:45"的條數,按上邊數據來看應該是一條都沒有。
我們先試用to_timestamp看看,確實一條都查不出來(因為"2021-01-05 08:29:45"其實就是"2021-01-05 08:29:45.000"):
22:27:55 ZKM@test(1028)> select * from aa where sample_time <= to_timestamp('2021-01-05 08:29:45','yyyy-mm-dd hh24:mi:ss'); no rows selected Elapsed: 00:00:00.01
顯然表中最小的2021-01-05 08:29:45.993比條件2021-01-05 08:29:45.000還要大,因此沒有符合條件的數據。
但是如果查找aa表中時間小於等於"2021-01-05 08:29:45.993"的條數,那就會有一條符合:
22:27:59 ZKM@test(1028)> select * from aa where sample_time <= to_timestamp('2021-01-05 08:29:45.993','yyyy-mm-dd hh24:mi:ss.ff'); SAMPLE_TIME --------------------------------------------------------------------------- 2021-01-05 08:29:45.993 Elapsed: 00:00:00.01
如果使用to_date的話,查找aa表中時間小於等於"2021-01-05 08:29:45"的條數,一樣的道理,不會有數據:
22:28:06 ZKM@test(1028)> select * from aa where sample_time <= to_date('2021-01-05 08:29:45','yyyy-mm-dd hh24:mi:ss'); no rows selected Elapsed: 00:00:00.01
由於date類型精確度的問題,無法使用類似"2021-01-05 08:29:45.993"的寫法,若是要出現這條數據,只能45s出改為46s。
22:28:43 ZKM@test(1028)> select * from aa where sample_time <= to_date('2021-01-05 08:29:46','yyyy-mm-dd hh24:mi:ss'); SAMPLE_TIME --------------------------------------------------------------------------- 2021-01-05 08:29:45.993 Elapsed: 00:00:00.00
結論
時間戳類型直接和時間類型做比較是可以的,稍微注意下精度的問題即可。