MySQL PERIOD_DIFF() Function
The PERIOD_DIFF()
function in MySQL calculates the difference between two periods, returning the number of months between them. This is particularly useful when you need to work with time intervals expressed in months.
PERIOD_DIFF(): Definition and Usage
PERIOD_DIFF()
takes two periods as input. A period is represented as YYYYMM or YYMM, where YYYY is the year and MM is the month. The function calculates the difference between these two periods in months. The order of the periods matters; the difference is calculated as `period1 - period2`.
Syntax
Syntax
PERIOD_DIFF(period1, period2)
Parameter Values
Parameter | Description |
---|---|
period1 |
The first period (YYYYMM or YYMM). This is required. |
period2 |
The second period (YYYYMM or YYMM). This is required. |
Examples
Calculating the Difference in Months
This example calculates the difference in months between October 2017 and March 2017.
Syntax
SELECT PERIOD_DIFF(201710, 201703);
Output
7
More Examples
These examples show additional calculations using different period values.
Syntax
SELECT PERIOD_DIFF(201703, 201803); --Difference across years
SELECT PERIOD_DIFF(1703, 1612); --Using YYMM format
Output
-12
13