DATEDIFF() in SQL
Calculates the difference between two dates in specified interval units.
Syntax
Return type
DATEDIFF() Function Example
What is DATEDIFF() in SQL?
The DATEDIFF()
function in SQL calculates the difference between two dates in a specified time interval (such as days, months, or years). It is commonly used for age calculations, duration measurements, and event tracking.
This function is primarily supported in SQL Server. For other databases:
MySQL & PostgreSQL use
DATEDIFF(start_date, end_date)
, but only return the difference in days.Oracle calculates the difference directly by subtracting two dates.
Syntax (SQL Server)
Output: 364
(number of days between the two dates).
The function supports multiple interval units, such as:
YEAR
→ Difference in years.MONTH
→ Difference in months.DAY
→ Difference in days.HOUR
,MINUTE
,SECOND
for time-based calculations.
It is widely used in reporting, scheduling, and historical data analysis.
Parameters:
interval_type: Unit to measure difference (year, month, day, hour, minute, second)
start_date: Beginning date
end_date: Ending date
Example Use Cases:
-- Calculate order processing time
-- Find customer age
-- Calculate project duration
Notes:
Behavior: Returns NULL if either date is NULL
Performance Considerations: Integer arithmetic is efficient
Version Info: Syntax varies by DBMS
Deprecated/Recommended Alternatives: None
Error Handling:
Error: Returns NULL for invalid dates
Recommendation: Validate date inputs before calculation
Supported Databases:
DBMS
Function / Syntax
Example
Behavior with NULL
MySQL
DATEDIFF(), TIMESTAMPDIFF()
DATEDIFF(date1, date2)
Returns NULL
PostgreSQL
AGE(), - operator
date1 - date2
Returns NULL
SQL Server
DATEDIFF()
DATEDIFF(day, date1, date2)
Returns NULL
SQLite
julianday()
julianday(date2) - julianday(date1)
Returns NULL
BigQuery
DATE_DIFF(), TIMESTAMP_DIFF()
DATE_DIFF(date2, date1, DAY)
Returns NULL
Snowflake
DATEDIFF()
DATEDIFF(day, date1, date2)
Returns NULL
Athena
DATE_DIFF()
DATE_DIFF(day, date1, date2)
Returns NULL