Date Spine

Create a table that lists all possible dates. Run once.

DROP TABLE IF EXISTS public.date_spine;

CREATE TABLE IF NOT EXISTS public.date_spine (
  id serial,
  date date

INSERT INTO public.date_spine (date)
SELECT CAST('1970-01-01' AS date) + generate_series(0, 365*100);

CREATE INDEX ON public.date_spine(date);


A date spine table is useful for any use case that requires rows of dates where no dates exists in the original data.
For example in an employee turnover use case, you might have data that looks like this:
To show how many employees were at the company on any given day you need a different data structure, one that has every possible date and everyone who was at the company on those dates.
To solve this you need a master date / calendar table.

What are the building blocks?

This is the simplest version that just lists the dates from a starting date and forward N number of days.
SELECT CAST(‘2015-01-01’ AS date) + generate_series(0, 365*100) AS dates;
Generate series is creating the series of numbers from 0 to N. In this case its ~100 years (365*109).
This is the result of the date spine SQL.