MySQL DATEDIFF Function

MySQL DATEDIFF function is one of the Date Functions, which is useful to find the difference between two dates and returns the number of days. Let us see how to use this MySQL Datediff function to find the difference between dates with example.

MySQL DATEDIFF Syntax

The basic syntax of the DATEDIFF Function in MySQL is as shown below:

DATEDIFF(Expression1, Expression2);

The DATEDIFF function subtracts Date Expression2 from Expression1 (Expression1 – Expression2) and returns the value. It won’t consider the Time value into consideration.

MySQL DATEDIFF function Example

The below-shown queries help you understand the use of this MySQL Date Difference function. Here, we are finding the difference in the total number of days between Date and time expression.

SELECT DATEDIFF('2019-02-28', '2019-01-01');

SELECT DATEDIFF('2019-02-28', '2019-12-31');

SELECT DATEDIFF('2019-02-28 12:11:22', '2019-12-31');
MySQL DATEDIFF Function 1

In this MySQL example, we are finding the difference between the Custom Dates and the current date and time returned by the Now(), CURDATE, and CURRENT_TIMESTAMP function.

SELECT NOW(), DATEDIFF(NOW(), '2018-12-31');

SELECT CURDATE(), DATEDIFF(CURDATE(), '2017-12-31');

SELECT CURRENT_TIMESTAMP, DATEDIFF(CURRENT_TIMESTAMP, '2018-01-31');
MySQL DATEDIFF Function 2

MySQL Date Difference Example 2

In this example, we show you how to use this MySQL Date Difference function on a table. Here, we are finding the difference between the current date and Employees Hire date using the datediff function.

SELECT EmpID, 
       FirstName,
       LastName,
       Occupation,
       YearlyIncome,
       Sales,
       HireDate,
       DATEDIFF(NOW(), HireDate) AS 'DATEDIFF Example'
 FROM `MySQL Tutorial`.customer;
MySQL DATEDIFF Function 3