sql - Reason for using trunc function on dates in Oracle -


i working in project on oracle database. have observed in application code dates never used directly. instead, used in conjunction trunc function (trunc(sysdate), trunc(event_date), etc.)

can explain reason behind using trunc function instead of using date directly?

a date in oracle has not date part, time part. can lead surprising results when querying data, e.g. query

with v_data(pk, dt) (   select 1, to_date('2014-06-25 09:00:00', 'yyyy-mm-dd hh24:mi:ss') dual union   select 2, to_date('2014-06-26 09:00:00', 'yyyy-mm-dd hh24:mi:ss') dual union     select 3, to_date('2014-06-27 09:00:00', 'yyyy-mm-dd hh24:mi:ss') dual) select * v_data dt = date '2014-06-25'   

will return no rows, since you're comparing 2014-06-25 @ midnight.

the usual workaround use trunc() rid of time part:

with v_data(pk, dt) (   select 1, to_date('2014-06-25 09:00:00', 'yyyy-mm-dd hh24:mi:ss') dual union   select 2, to_date('2014-06-26 09:00:00', 'yyyy-mm-dd hh24:mi:ss') dual union     select 3, to_date('2014-06-27 09:00:00', 'yyyy-mm-dd hh24:mi:ss') dual) select * v_data trunc(dt) = date '2014-06-25'   

other, less used approaches problem include:

  • convert both dates to_char('yyyy-mm-dd') , check equality
  • use between clause: where dt between date '2014-06-25' , date '2014-06-26'

Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

Python ctypes access violation with const pointer arguments -