Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL: Get records created in time range for specific dates

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?

like image 591
Mouna Cheikhna Avatar asked Mar 05 '12 15:03

Mouna Cheikhna


2 Answers

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.

like image 122
APC Avatar answered Oct 20 '22 15:10

APC


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' 
like image 39
Doug Porter Avatar answered Oct 20 '22 17:10

Doug Porter