• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 26374
  • Last Modified:

How to compare a time in Oracle?


I need to retrieve record from the Oracle database by comparing with a time range? The column "OTime" is of Date datatype. I'm using ASP.

This is my SQL:
"SELECT * FROM Purchase WHERE (OTime BETWEEN to_date('" & from_time & "', 'HH24:MI:SS') AND to_date('"& to_time &"', 'HH24:MI:SS'))

There are no errors, but no records were retrieved. I have only stored the time into "OTime". Do I need to store the date as well?


1 Solution
Try something like this

Select * from Purchase
where to_date(to_char(OTIME,'hh24miss'),'hh24miss')
            between to_date('070000','hh24miss') and to_date('080000','hh24miss')

DATE type in Oracle allways stores date and time. It seems that the SYSDATE is stored as date component.


"SELECT * FROM Purchase WHERE (to_date(OTime,'HH24:MI:SS') BETWEEN to_date('" & from_time & "', 'HH24:MI:SS') AND to_date('"&
to_time &"', 'HH24:MI:SS'))
For the datatype of DATE Oracle always stores both date and time. If you need just the date, you can use trunc() function to put the time at midnight, but you have not an option to store only the time. So I'm wordering how you did it? However, thinking that in OTime field actually you have a datetime, you might be able to solve the problem.
Using to_date() with format mask of 'HH24:MI:SS' will be interpreded as SYSDATE with the time specified. However, I think your query will return error, because from time and to time parameters are not correctly used. The query should look like:

SELECT * FROM Purchase
 WHERE (OTime BETWEEN to_date('&from_time', 'HH24:MI:SS')
          AND to_date('&to_time', 'HH24:MI:SS'))

and thinking that we have the date included, to ignore it we may use:

SELECT * FROM Purchase
 WHERE (to_char(OTime,'HH24MISS') BETWEEN '&from_time'
        and '&to_time')

I guess this is not only the solution and to_char() will stop oracle to use any indexes of OTime column, except you have version >=8 and can use index based on function.
Good Luck.
a variable of date datatype allways holds day/month/year information
so if you
  vTime DATE;
  SELECT to_date('13:27:11','HH24:MI:SS') INTO vTime FROM dual;
vTime is this day, time 13:27:11, today 21-mar-2002 13:27:11

so if you want to compare only time you should convert it into number or char and compare chars

Featured Post

Upgrade your Question Security!

Add Premium security features to your question to ensure its privacy or anonymity. Learn more about your ability to control Question Security today.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now