Search code examples
sqloracledate-arithmetic

Oracle query to fetch every minute between two timestamps


I need a oracle query which returns every minute between given two timestamps. I referred this Stack Overflow question. Can we improve the same query?


Solution

  • To get all the minutes between two datetime elements using Row Generator technique, you need to convert the difference between the dates into the number of minutes. Rest remains same in the CONNECT BY clause.

    For example, to get all the minutes between 11/09/2015 11:00:00 and 11/09/2015 11:15:00:

    SQL> WITH DATA AS
      2    (SELECT to_date('11/09/2015 11:00:00', 'DD/MM/YYYY HH24:MI:SS') date_start,
      3      to_date('11/09/2015 11:15:00', 'DD/MM/YYYY HH24:MI:SS') date_end
      4    FROM dual
      5    )
      6  SELECT TO_CHAR(date_start+(LEVEL -1)/(24*60), 'DD/MM/YYYY HH24:MI:SS') the_date
      7  FROM DATA
      8    CONNECT BY level <= (date_end - date_start)*(24*60) +1
      9  /
    
    THE_DATE
    -------------------
    11/09/2015 11:00:00
    11/09/2015 11:01:00
    11/09/2015 11:02:00
    11/09/2015 11:03:00
    11/09/2015 11:04:00
    11/09/2015 11:05:00
    11/09/2015 11:06:00
    11/09/2015 11:07:00
    11/09/2015 11:08:00
    11/09/2015 11:09:00
    11/09/2015 11:10:00
    11/09/2015 11:11:00
    11/09/2015 11:12:00
    11/09/2015 11:13:00
    11/09/2015 11:14:00
    11/09/2015 11:15:00
    
    16 rows selected.
    

    Above, CONNECT BY level <= (date_end - date_start)*(24*60) +1 means that we are generating rows as many as the number (date_end - date_start)*(24*60) +1. You get 16 rows, because it includes both the start and end window for the minutes.