Getting a date list in a range in PostgreSQL
In PostgreSQL we can generate_series for creating a date range series. To get daily dates from '2023-01-01' to '2023-01-10', use the following query:
Simple like a Sunday morning, the query pumps out a column of dates for your range, with one row for each day.
The flexibility of generate_series
The generate_series
function is about as flexible as a contortionist. You can adapt it to get weekly intervals:
Or perhaps you prefer monthly intervals:
Just replace '1 day'::interval
with any other time unit you need.
Power level: Over 9,000
For more intricate demands, like specific business days or custom sequences, you'd want to consider carving your own persistent date table and conjuring Custom Sequences with CTE
. Persistent date tables are like your cup of strong coffee for dealing with complex, repeated operations.
date_table
makes operations like excluding weekends feel as though you're taking a walk in the park:
For complex queries, a Common Table Expression (CTE) is the shining beacon in your code's structuring needs:
When data types throw a party
Always confirm if the data types are having a blast together. For timestamp
, party like this:
Here, the dates and the generate_series get along since they're both timestamps
.
Special date ranges, special attention
For special ranges, such as holidays or working days, the query gets an added layer of logic:
This query uses a subselect to excise dates that are holidays.
Time zone gotchas
Time zones and daylight saving changes can mess with date generation. Here's how to deal with that:
Pop! Time zone problems are no more!
Analysis and performance? Level up!
A persistent dates table can supercharge your analysis and query performance. A caboose to your data analysis train.
Was this article helpful?