MariaDB TIMESTAMPDIFF() Function
In MariaDB, TIMESTAMPDIFF() is a built-in function that returns the difference between two datetimes.
MariaDB TIMESTAMPDIFF() Syntax
This is the syntax of the MariaDB TIMESTAMPDIFF() function:
TIMESTAMPDIFF(unit, datetime1, datetime2)
Parameters
unit-
Required. The unit of return, available values ββare:
MICROSECOND,SECOND,MINUTE,HOUR,DAY, ,WEEK,MONTH,QUARTER,YEAR. datetime1-
Required. A datetime value or expression.
datetime2-
Required. A datetime value or expression.
If you supply the wrong number of arguments, MariaDB will report an error: ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ')' at line 1.
Return value
MariaDB TIMESTAMPDIFF() function returns the difference between two dates/datetimes.
If either argument is NULL, the TIMESTAMPDIFF() function will return NULL.
MariaDB TIMESTAMPDIFF() Examples
Example 1 - date value
This statement returns the number of days between two dates using the MariaDB TIMESTAMPDIFF() function:
SELECT TIMESTAMPDIFF(DAY, '2023-01-01', '2023-01-12');
Output:
+------------------------------------------------+
| TIMESTAMPDIFF(DAY, '2023-01-01', '2023-01-12') |
+------------------------------------------------+
| 11 |
+------------------------------------------------+Example 2 - datetime value
This statement returns the number of seconds between two dates using the MariaDB TIMESTAMPDIFF() function:
SELECT TIMESTAMPDIFF(SECOND, '2023-01-01 10:12:13', '2023-01-01 10:12:14') Result;
Output:
+--------+
| Result |
+--------+
| 1 |
+--------Example 3 - Negative values
If the first time is later than the second parameter, the MariaDB TIMESTAMPDIFF() function will return a negative value:
SELECT TIMESTAMPDIFF(DAY, '2023-01-12', '2023-01-01');
Output:
+------------------------------------------------+
| TIMESTAMPDIFF(DAY, '2023-01-12', '2023-01-01') |
+------------------------------------------------+
| -11 |
+------------------------------------------------+Conclusion
In MariaDB, TIMESTAMPDIFF() is a built-in function that returns the difference between two datetimes.