Skip to content
Advertisement

Generate_series in Postgres from start and end date in a table

I have been trying to generate a series of dates (YYYY-MM-DD HH) from the first until the last date in a timestamp field. I’ve got the generate_series() I need, however running into an issue when trying to grab the start and end dates from a table. I have the following to give a rough idea:

Postgres 9.3

Advertisement

Answer

You don’t need a CTE for this, that would be more expensive than necessary.
And you don’t need to cast to timestamp, the result already is of data type timestamp when you feed timestamp types to generate_series(). Details here:

In Postgres 9.3 or later you can use a LATERAL join:

Optionally with to_char() to get the result as text in the format you mentioned.

This works in any Postgres version:

Typically a bit faster.
Calling set-returning functions in the SELECT list is a non-standard-SQL feature and frowned upon by some. Also, there were behavioral oddities (though not for this simple case) that were eventually fixed in Postgres 10. See:

Note a subtle difference in NULL handling:

The equivalent of

is obtained with

Without NULLS LAST NULL values come first in descending order (if there can be NULL values in start_timestamp). You would get NULL for last_date and your query would come up empty.

Details:

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement