I have a set of records that were created last week, and from those I want to retrieve only those that were created between 6h45 and 19h15. I have a column creation_date
that I can use.
How can I do this in sql?
In Oracle we can turn dates into numbers and apply arithmetic to them in a variety of ways.
For instance sysdate-7
gives us the date seven days ago. trunc(some_date)
removes the time element from a date column. And to_char(some_date, 'SSSSS')
gives us its time element as the number of seconds since midnight. So 06:45:00 is 24300 seconds and 18:15:59 is 69359 seconds (please check those numbers, as they are back-of-an-envelope figgerin').
Anyway, putting that all together in a single query like this ...
select *
from your_table
where creation_date >= trunc(sysdate)-7
and to_number(to_char(creation_date, 'sssss')) between 24300 and 69359
... wil produce all the records created in the last week with a time element within core hours.
This query would return any records created in the last 7 days with the time portion of their create date between 6:45am and 7:15pm.
select *
from your_table
where creation_date > sysdate - 7
and to_char(creation_date, 'hh24:mi:ss') >= '06:45:00'
and to_char(creation_date, 'hh24:mi:ss') <= '19:15:00'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With