|
| 1 | +--- |
| 2 | +title: MONTHS_BETWEEN |
| 3 | +--- |
| 4 | +import FunctionDescription from '@site/src/components/FunctionDescription'; |
| 5 | + |
| 6 | +<FunctionDescription description="Introduced or updated: v1.2.307"/> |
| 7 | + |
| 8 | +Returns the number of months between *date1* and *date2*. |
| 9 | + |
| 10 | +## Syntax |
| 11 | + |
| 12 | +```sql |
| 13 | +MONTHS_BETWEEN( <date1>, <date2> ) |
| 14 | +``` |
| 15 | + |
| 16 | +## Arguments |
| 17 | + |
| 18 | +*date1* and *date2* can be of DATE type, TIMESTAMP type, or a mix of both. |
| 19 | + |
| 20 | +## Return Type |
| 21 | + |
| 22 | +The function returns a FLOAT value based on the following rules: |
| 23 | + |
| 24 | +- If *date1* is earlier than *date2*, the function returns a negative value; otherwise, it returns a positive value. |
| 25 | + |
| 26 | + ```sql title='Example:' |
| 27 | + SELECT |
| 28 | + MONTHS_BETWEEN('2024-03-15'::DATE, |
| 29 | + '2024-02-15'::DATE), |
| 30 | + MONTHS_BETWEEN('2024-02-15'::DATE, |
| 31 | + '2024-03-15'::DATE); |
| 32 | + |
| 33 | + -[ RECORD 1 ]----------------------------------- |
| 34 | + months_between('2024-03-15'::date, '2024-02-15'::date): 1 |
| 35 | + months_between('2024-02-15'::date, '2024-03-15'::date): -1 |
| 36 | + ``` |
| 37 | + |
| 38 | +- If *date1* and *date2* fall on the same day of their respective months or both are the last day of their respective months, the result is an integer. Otherwise, the function calculates the fractional portion of the result based on a 31-day month. |
| 39 | + |
| 40 | + ```sql title='Example:' |
| 41 | + SELECT |
| 42 | + MONTHS_BETWEEN('2024-02-29'::DATE, |
| 43 | + '2024-01-29'::DATE), |
| 44 | + MONTHS_BETWEEN('2024-02-29'::DATE, |
| 45 | + '2024-01-31'::DATE); |
| 46 | +
|
| 47 | + -[ RECORD 1 ]----------------------------------- |
| 48 | + months_between('2024-02-29'::date, '2024-01-29'::date): 1 |
| 49 | + months_between('2024-02-29'::date, '2024-01-31'::date): 1 |
| 50 | +
|
| 51 | + SELECT |
| 52 | + MONTHS_BETWEEN('2024-08-05'::DATE, |
| 53 | + '2024-01-01'::DATE); |
| 54 | +
|
| 55 | + -[ RECORD 1 ]----------------------------------- |
| 56 | + months_between('2024-08-05'::date, '2024-01-01'::date): 7.129032258064516 |
| 57 | + ``` |
| 58 | + |
| 59 | +- If *date1* and *date2* are the same date, the function ignores any time components and returns 0. |
| 60 | + |
| 61 | + ```sql title='Example:' |
| 62 | + SELECT |
| 63 | + MONTHS_BETWEEN('2024-08-05'::DATE, |
| 64 | + '2024-08-05'::DATE), |
| 65 | + MONTHS_BETWEEN('2024-08-05 02:00:00'::TIMESTAMP, |
| 66 | + '2024-08-05 01:00:00'::TIMESTAMP); |
| 67 | +
|
| 68 | + -[ RECORD 1 ]----------------------------------- |
| 69 | + months_between('2024-08-05'::date, '2024-08-05'::date): 0 |
| 70 | + months_between('2024-08-05 02:00:00'::timestamp, '2024-08-05 01:00:00'::timestamp): 0 |
| 71 | + ``` |
0 commit comments