How can we ignore the negative values return by MySQL DATEDIFF() function?

MySQLMySQLi Database

As we know that DATEDIFF() function is used to get the difference in a number of days between two dates. Hence, it is quite possible that it returns negative value as well.

mysql> select * from differ;
+------------+-------------+
| OrderDate  | WorkingDate |
+------------+-------------+
| 2017-10-22 | 2017-10-29  |
| 2017-10-25 | 2017-10-30  |
| 2017-10-25 | 2017-11-30  |
+------------+-------------+
3 rows in set (0.00 sec)

Above query will return the values from table ‘differ’. Now, if someone wants to get the difference between OrderDate and WorkingDate then the output would be negative as follows −

mysql> Select DATEDIFF(OrderDate, WorkingDate)AS 'DIFFERENCE IN DAYS' from differ;
+--------------------+
| DIFFERENCE IN DAYS |
+--------------------+
|                 -7 |
|                 -5 |
|                -36 |
+--------------------+
3 rows in set (0.00 sec)

But we can use MySQL ABS() function to ignore these negative values and it can be done as follows −

mysql> Select ABS(DATEDIFF(OrderDate, WorkingDate))AS 'DIFFERENCE IN DAYS' from differ;
+--------------------+
| DIFFERENCE IN DAYS |
+--------------------+
|                  7 |
|                  5 |
|                 36 |
+--------------------+
3 rows in set (0.00 sec)
raja
Published on 19-Feb-2018 10:32:42
Advertisements