How do you calculate the difference between two dates in SQL?
Posted by BobHarris
Last Updated: August 04, 2024
Calculating the difference between two dates in SQL can vary slightly depending on the database management system (DBMS) you are using. Here are examples for different systems:
1. MySQL
In MySQL, you can use the DATEDIFF() function to get the difference in days between two dates:
SELECT DATEDIFF('2023-10-31', '2023-10-01') AS date_difference;
If you want the difference in other units, you can use TIMESTAMPDIFF():
SELECT TIMESTAMPDIFF(DAY, '2023-10-01', '2023-10-31') AS days_difference,
       TIMESTAMPDIFF(HOUR, '2023-10-01', '2023-10-31') AS hours_difference;
2. PostgreSQL
In PostgreSQL, you can simply subtract two dates, which will give you the difference in days:
SELECT '2023-10-31'::date - '2023-10-01'::date AS date_difference;
For a more detailed difference, you can use AGE() function:
SELECT AGE('2023-10-31', '2023-10-01') AS date_difference;
3. SQL Server
In SQL Server, you can use the DATEDIFF() function to calculate the difference in specified units:
SELECT DATEDIFF(DAY, '2023-10-01', '2023-10-31') AS days_difference,
       DATEDIFF(HOUR, '2023-10-01', '2023-10-31') AS hours_difference;
4. Oracle
In Oracle, you can simply subtract two dates, which gives you the difference in days:
SELECT (TO_DATE('2023-10-31', 'YYYY-MM-DD') - TO_DATE('2023-10-01', 'YYYY-MM-DD')) AS date_difference FROM dual;
To get the difference in other units, you might need to multiply/divide by appropriate values:
SELECT (TO_DATE('2023-10-31', 'YYYY-MM-DD') - TO_DATE('2023-10-01', 'YYYY-MM-DD')) * 24 AS hours_difference FROM dual;
Summary
- MySQL: Use DATEDIFF() or TIMESTAMPDIFF(). - PostgreSQL: Simply subtract dates or use AGE(). - SQL Server: Use DATEDIFF(). - Oracle: Subtract dates or use calculations for other units. Make sure to adjust the formats and functions based on your DBMS!