Re: Understanding years part of Interval

From: Marcos Pegoraro <marcos(at)f10(dot)com(dot)br>
To: pgsql-hackers <pgsql-hackers(at)postgresql(dot)org>
Subject: Re: Understanding years part of Interval
Date: 2023-02-07 12:00:03
Message-ID: CAB-JLwYwtA70Fg92uHJWytYpDa6mkV8MYnYexjaDcdTM=ZnfrQ@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general pgsql-hackers

>
> The years are converted to months and the fractional month is rounded half
>> up:
>>
>> 1.05 year = 12.6 month
>> => 1 year 0.6 month
>> => 1 year 1 month (after rounding)
>>
>> Compare that to 12.5 months to see when the rounding occurs:
>>
>> 12.5 month / 12 month
>> => 1.0416... years
>>
>> Plug 1.0416 and 1.0417 into the interval to observe the rounding:
>>
>> =# select '1.0416 year'::interval, '1.0417 year'::interval;
>> interval | interval
>> ----------+--------------
>> 1 year | 1 year 1 mon
>>
>> I understood what you explained, but cannot agree that it's correct.
> Run these and you'll see the first and second select are fine, the third
> ... why ?
>
> select distinct current_date + ((random()::numeric) * '1 year'::interval)
> from generate_series(1,100) order by 1;
> select distinct current_date + ((random()::numeric) * '12
> month'::interval) from generate_series(1,100) order by 1;
> select distinct current_date + ((random()::numeric) || 'year')::interval
> from generate_series(1,100) order by 1;
>
> So, I have to think ... never use fractional parts on years, right ?
>

Only to be written, if somebody has to work with fractional parts of years.

This way works
select distinct (random()::numeric) * ('1 year'::interval) from
generate_series(1,100) order by 1;

This way doesn´t
select distinct ((random()::numeric) || 'year')::interval from
generate_series(1,100) order by 1;

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Rinat Shigapov 2023-02-07 12:00:48 Re: Too coarse predicate locks granularity for B+ tree indexes
Previous Message Matthias Apitz 2023-02-07 11:46:47 ERROR: deadlock detected

Browse pgsql-hackers by date

  From Date Subject
Next Message Rinat Shigapov 2023-02-07 12:00:48 Re: Too coarse predicate locks granularity for B+ tree indexes
Previous Message Pavel Borisov 2023-02-07 11:54:07 Re: Hi i am Intrested to contribute