Question

I'm trying to obtain a list of dates within range, similar to the command NOW() in PostgreSQL, with the only difference that now(), returns only the current date.

If I execute it as follows I obtain:

select now();

2013-09-27 15:27:50.303-05

Or by example, I could do this:

select now() - interval '1' day;

and the result is yesterday

2013-09-27 15:27:50.303-05

What I need is a query that could return a list with every date within a given range, so if I provide 2013-09-20 and 2013-09-27 (I'm nor really interested in hours, only dates) I would like to obtain an output as follows:

2013-09-20
2013-09-21
2013-09-22
2013-09-23
2013-09-24
2013-09-25
2013-09-26
2013-09-27

Any ideas on how to achieve this? By preference without using stored procedures or functions, unless there is no other way ...

Was it helpful?

Solution

Use generate_series(), does exactly what you need:

SELECT generate_series('2013-09-20'::date
                     , '2013-09-27'::date
                     , interval '1 day')::date;

Takes two timestamp variables, but dates are also accepted.
Returns timestamp with time zone, so I cast to date according to your request.

A more verbose, but syntactically clearer version is to use the set returning function (SRF) as FROM item:

SELECT *
FROM   generate_series('2013-09-20'::date
                     , '2013-09-27'::date
                     , interval '1 day')::date;

Consider the comments below.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top