Datediff Sql Function in SQL
? DATEDIFF() Function in SQL
The DATEDIFF() function calculates the difference between two dates and returns the result as an integer.
? Syntax Variations
SQL Server:
DATEDIFF(datepart, start_date, end_date)MySQL:
DATEDIFF(end_date, start_date)PostgreSQL:
No direct DATEDIFF() function, but you can subtract dates:
end_date - start_date? Parameters
| Parameter | Description |
|---|---|
datepart | (SQL Server only) Part of date to calculate difference (e.g., day, month, year) |
start_date | The starting date |
end_date | The ending date |
? Examples
SQL Server — Difference in days between two dates
SELECT DATEDIFF(day, '2025-06-01', '2025-06-06') AS DaysDifference;-- Result: 5SQL Server — Difference in months
SELECT DATEDIFF(month, '2025-01-01', '2025-06-01') AS MonthsDifference;-- Result: 5MySQL — Difference in days
SELECT DATEDIFF('2025-06-06', '2025-06-01') AS DaysDifference;-- Result: 5PostgreSQL — Difference in days (using subtraction)
SELECT '2025-06-06'::date - '2025-06-01'::date AS DaysDifference;-- Result: 5? Notes
SQL Server’s
DATEDIFFsupports manydatepartvalues likeyear,month,day,hour,minute, etc.MySQL’s
DATEDIFFonly returns the difference in days.In PostgreSQL, subtracting dates returns an integer number of days.
If you want examples for a specific SQL dialect or for other units like hours or minutes, just ask!