Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Number of days in a daterange

Tags:

postgresql

How do you extract the number of days from a column of type daterange? Is it possible?

I tried

select age(daterange('2018-01-01', '2018-02-01'));

But it fails, I also tried casting to int with out luck. I reviewed the docs but I was unable to find any function that could acomplish this in the range types.

like image 507
nanounanue Avatar asked Sep 15 '25 10:09

nanounanue


1 Answers

We can try using the upper() and lower() functions to find the upper and lower bound of the date range. Then, take the difference of these dates to find the number of days in between them:

SELECT
    UPPER(daterange('2018-01-01', '2018-02-01')) -
        LOWER(daterange('2018-01-01', '2018-02-01')) AS diff;

31

Note that the way you constructed your range is actually identical to this:

daterange('2018-01-01', '2018-02-01', '[)')

That is, the range is upper bound exclusive. As a result, only the 31 days of January 2018 are included in the count, but 1st February is excluded. If you instead wanted to include that date point as well, you could use this range:

daterange('2018-01-01', '2018-02-01', '[]')

Running the above query would then yield a day count of 32.

like image 106
Tim Biegeleisen Avatar answered Sep 18 '25 09:09

Tim Biegeleisen