MySQL PERIOD_DIFF() Function

MySQL PERIOD_DIFF() function; In this tutorial, i am going to show you MySQL period_diff() function with the help of examples.

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 two periods parameters used in this function should be in the same format

Syntax of MySQL PERIOD_DIFF() Function

The syntax of the period_diff() function is:

PERIOD_DIFF(P1,P2)

Here: P1 is the first period, and P2 is the second.

Example 1 – MySQL PERIOD_DIFF() Function

Let’s take first example of this period_diff() mysql function; as follows:

SELECT PERIOD_DIFF(201906, 201905);

Output-1

+-----------------------------+
| PERIOD_DIFF(201906, 201905) |
+-----------------------------+
|                           1 |
+-----------------------------+

Example 2 – MySQL PERIOD_DIFF() Function

Let’s take the second example of period_diff() function; as follows:

 SELECT PERIOD_DIFF(201905, 201907); 

Output-2

+-----------------------------+
| PERIOD_DIFF(201905, 201907) |
+-----------------------------+
|                          -2 |
+-----------------------------+ 

Example 3 – MySQL PERIOD_DIFF() Function

Let’s take another example of this, using the two digit year format like YYMM; as follows:

SELECT PERIOD_DIFF(1906, 1905);

Output-3

+-------------------------+
| PERIOD_DIFF(1906, 1905) |
+-------------------------+
|                       1 |
+-------------------------+

Example 4 – MySQL PERIOD_DIFF() with CURDATE Function

Let’s take the next example with the current date; as follows:

    SELECT 
    CURDATE( ) AS 'Current Date',
    EXTRACT(YEAR_MONTH FROM CURDATE( )) AS 'Current Period',
    201010 AS 'Previous Period',
    PERIOD_DIFF(EXTRACT(YEAR_MONTH FROM CURDATE( )), 201010) AS 'Difference';

Output-4

+--------------+----------------+-----------------+------------+
| Current Date | Current Period | Previous Period | Difference |
+--------------+----------------+-----------------+------------+
|  2019-07-20  |         201907 |          201010 |       105  |
+--------------+----------------+-----------------+------------+

Conclusion

MySQL PERIOD_DIFF() Function tutorial, you have learned how to use MySQL PERIOD_DIFF() function with various examples.

Be First to Comment

Leave a Reply

Your email address will not be published.