I am selecting list of periods from database. If current row is first row then the period starts with date and I can find the interval between period start like this:
SELECT
...
CASE WHEN row_number() OVER(ORDER BY r.created_at ASC) = 1 THEN r.created_at - r.created_at::date ELSE NULL END AS period
...
FROM mytable r
first
last
This might be faster than window functions:
with r as (
select
min(created_at) as min_created_at,
max(created_at) as max_created_at
from mytable
)
select
case when (select min_created_at from r) = created_at
then created_at - created_at::date else null
end as period_min,
case when (select max_created_at from r) = created_at
then created_at - created_at::date else null
end as period_max
from mytable