I'd like to get the list of days between the two dates (including them) in a PostgreSQL database. For example, if I had:
- start date: 29 june 2012
- end date: 3 july 2012
then the result should be:
29 june 2012
30 june 2012
1 july 2012
2 july 2012
3 july 2012
What would be the best way of doing this in PostgreSQL?
Thanks.
For things like this its generally handy to have a dates table in the system.
Just like a numbers table they can be very useful and quicker to use than generating the dates on the fly, especially when you scale up to large data sets.
Such a date table from 1900 to 2100 will be very small, so there isn't much over head in storage.
Edit: Dunno why this is getting voted down, it will probably be the best for performance. Plus it has so many other advantages. Want to link orders to a an quarters performance numbers? Its a simple link between the tables. (Order.OrderDate -> Dates.Date -> Dates.Quarter -> PerformanceTotal.Quarter) etc. Its the same for dealing with working days, like the last working day of a month, or the first Tuesday of the previous month. Like a numbers table, I'd strongly recommend them!
If you already have database that you want to query:
This will result in:
This should do it:
If you don't want to repeat the start_date in the subselect things get a bit more complicated:
(See maniek's answer for a much better version of the "no-repeat" problem)
This PLpg/SQL function would do the trick:
As
timestamp
:or casted to
date
: