MySQL PERIOD_DIFF() function
In this context, we will learn how we can use the MySQL PERIOD_DIFF() function with proper syntax and good examples.
Introduction of MySQL PERIOD_DIFF() function
This function in MySQL is used to return the difference between two specified periods. Here the returned results will be in months (either negative or positive), and the two period parameters used in this function should be in the same format.
Syntax of the MySQL PERIOD_DIFF() function
The syntax of the MySQL PERIOD_DIFF() function is given as follows:
PERIOD_DIFF(period1, period2)
Parameters or arguments used in MySQL PERIOD_DIFF() function:
There are two parameters accepted by the PERIOD_DIFF() function in MySQL, which are given as follows:
Period1: This is the specified first period in the format of YYMM or YYYYMM.
Period2: The specified second period in the format of YYMM or YYYYMM.
Returns:
It will return the difference between two specified period values.
Application used for PERIOD_DIFF() function:
The PERIOD_DIFF() function can be used in the given below MySQL versions.:
- MySQL 5.7
- MySQL 5.6
- MySQL 5.5
- MySQL 5.1
- MySQL 5.0
- MySQL 4.1
- MySQL 4.0
- MySQL 3.23
Examples of MySQL PERIOD_DIFF() function:
Now we will look into some MySQL PERIOD_DIFF() function examples and will explore how we can use the PERIOD_DIFF function in MySQL.
Example-1 :
In this example, the parameters are used in the format of YYMM, and the returned month is negative because the period1 is less than period2.
SELECT PERIOD_DIFF(2002, 2011);
Output:
-9
1 row in set (0.00 sec)
Example-2 :
In this example, the parameters are used in the format of YYMM, and the returned month is positive because the period1 is greater than period2.
SELECT PERIOD_DIFF(2020, 2006);
Output:
14
1 row in set (0.00 sec)
Example-3 :
In this example, the parameters are used in the format of YYYYMM, and the returned month is negative because period 1 is less than period 2.
SELECT PERIOD_DIFF(202005, 202010);
Output:
-5
1 row in set (0.00 sec)
Example-4 :
In this example, the parameters are used in the format of YYYYMM in MySQL, and the returned month is positive because period 1 is greater than period 2.
SELECT PERIOD_DIFF(202014, 202009);
Output:
5
1 row in set (0.00 sec)
Application of MySQL PERIOD_DIFF() function:
This function is used to return the difference between two specified periods.
Summary:
In the above context, we have learned how to use the PERIOD_DIFF() function in MySQL to return the difference between two specified periods.