Predictive Hacks

How to Generate Date Series in PostgreSQL

In many SQL statements, there is a need to generate “Date Series” and then run some left join statements in order to build the required report. Let’s see how we can generate Date Series in PostgreSQL. In this example, we will generate monthly date series, going back two years ago up to now.

SELECT generate_series((date_trunc('year', current_date)  - interval  '2 year'), current_date, '1 month')::date AS gdate
order by 1

You can easily change the parameters insider the generate_series function in order to generate series daily or annual series and so on. You can also change the frequency. Let’s say that we want date series every month months.

SELECT generate_series((date_trunc('year', current_date)  - interval  '2 year'), current_date, '4 month')::date AS gdate
order by 1

Share This Post

Share on facebook
Share on linkedin
Share on twitter
Share on email

Subscribe To Our Newsletter

Get updates and learn from the best

More To Explore

Python

Image Captioning with HuggingFace

Image captioning with AI is a fascinating application of artificial intelligence (AI) that involves generating textual descriptions for images automatically.

Python

Intro to Chatbots with HuggingFace

In this tutorial, we will show you how to use the Transformers library from HuggingFace to build chatbot pipelines. Let’s