MONTHS_BETWEEN
functionsupportedCore SQL functionsReturns the number of months between two DATE or TIMESTAMP values. For example, MONTHS_BETWEEN('2020-02-01'::DATE, '2020-01-01'::DATE) returns 1.0.
Syntax
MONTHS_BETWEEN( <date_expr1> , <date_expr2> )
Parameters
| Name | Required | Description |
|---|---|---|
date_expr1 | required | The date to subtract from. |
date_expr2 | required | The date to subtract. |
Returns
A FLOAT representing the number of months between the two dates. The number is calculated as described below: - The integer portion of the FLOAT is calculated using the year and month parts of the input values. - In most situations, the fractional portion is calculated using the day and time parts of the input values. (When calculating the fraction of a month, the function considers each month to be 31 days long.) However, there are two exceptions: If the days of the month are the same (e.g. February 28 and March 28), the fractional portion is zero, even if one or both input values are timestamps and the times differ. - If the days of the month are both the last day of the month (e.g. February 28 and March 31), the fractional portion is zero, even if the days of the month are not the same. For example, the function considers each of the following pairs of dates/timestamps to be exactly 1.0 months apart:
Usage notes
- If date (or timestamp) d1 represents an earlier point in time than d2, then MONTHS_BETWEEN(d1, d2) returns a negative value; otherwise it returns a positive value. More generally, swapping the inputs reverses the sign: MONTHS_BETWEEN(d1, d2) = -MONTHS_BETWEEN(d2, d1).
- You can use a DATE value for one input parameter and a TIMESTAMP for the other.
- If you use one or more TIMESTAMP values but do not want fractional differences based on time of day, then cast your TIMESTAMP expressions to DATE.
- If you only want integer values, you can truncate, round, or cast the value. For example: Copy code SELECT ROUND(MONTHS_BETWEEN('2019-03-31 12:00:00'::TIMESTAMP, '2019-02-28 00:00:00'::TIMESTAMP)) AS MonthsBetween1; +----------------+ | MONTHSBETWEEN1 | |----------------| | 1 | +----------------+
- If any input is NULL, the result is NULL.