Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate a range of dates using SQL

Tags:

sql

oracle

I have a SQL query that takes a date parameter (if I were to throw it into a function) and I need to run it on every day of the last year.

How to generate a list of the last 365 days, so I can use straight-up SQL to do this?

Obviously generating a list 0..364 would work, too, since I could always:

SELECT SYSDATE - val FROM (...); 
like image 487
George Mauer Avatar asked Jan 06 '09 21:01

George Mauer


People also ask

How do I create a list of dates in SQL?

Now, in order to generate all the dates in the sale report, first we are generating a list of all dates between start and end date using recursive CTE and then using Left Join with the existing query to display all the dates in the result. Related posts: Generate Weekdays in SQL Server.

How do I generate days between two dates in SQL?

SQL Server DATEDIFF() Function The DATEDIFF() function returns the difference between two dates.


1 Answers

There's no need to use extra large tables or ALL_OBJECTS table:

SELECT TRUNC (SYSDATE - ROWNUM) dt   FROM DUAL CONNECT BY ROWNUM < 366 

will do the trick.

like image 98
user34850 Avatar answered Sep 22 '22 07:09

user34850