The datediff function in SQL Server calculates the difference between two dates in a specified interval-such as days, months, or years-and returns an integer. It's used to measure elapsed time between events, validate deadlines, or analyze temporal patterns in data.
When you run SELECT DATEDIFF(day, '2023-01-01', '2023-12-31'), SQL Server returns 364, representing the number of days between January 1 and December 31, 2023. The function takes three arguments: the interval unit, the start date, and the end date. It does not count partial intervals-it truncates, not rounds.
This function is part of SQL Server's built-in date and time functions, which include GETDATE(), DATEADD(), and CONVERT(). It operates on DATETIME, DATETIME2, and SMALLDATETIME data types. You cannot use it with strings unless they're explicitly cast to a valid date format.
DATEDIFF evaluates the difference between two timestamps based on the unit you specify. For example, second, minute, hour, day, month, quarter, or year. The result is always an integer, even if the actual time span includes fractions.
If you compare '2023-03-15 14:30:00' and '2023-03-15 14:30:59' using DATEDIFF(second, ...), the result is 59. But if you use minute, the result is 0 because both times fall within the same minute. This behavior often trips up developers who expect fractional results.
Internally, SQL Server uses a 100-nanosecond tick system. It subtracts the internal representation of the start time from the end time, then divides by the tick count for the requested unit. This ensures consistent results across different time zones when using UTC-based values.
Here's a table of supported units and their effects:
| Unit | Example | Result |
|---|---|---|
second |
DATEDIFF(second, '2023-01-01 00:00:00', '2023-01-01 00:00:30') |
30 |
minute |
DATEDIFF(minute, '2023-01-01 12:00:00', '2023-01-01 12:30:00') |
30 |
hour |
DATEDIFF(hour, '2023-01-01 08:00:00', '2023-01-01 17:00:00') |
9 |
day |
DATEDIFF(day, '2023-01-01', '2023-01-02') |
1 |
month |
DATEDIFF(month, '2023-01-01', '2023-04-01') |
3 |
year |
DATEDIFF(year, '2020-01-01', '2023-01-01') |
3 |
Using quarter or week gives results based on calendar boundaries. For example, DATEDIFF(week, '2023-01-01', '2023-01-07') returns 1, even though the gap is only six days. That's because SQL Server counts the number of week boundaries crossed-not the actual elapsed days.
A common mistake is assuming DATEDIFF(day, '2023-01-01', '2023-01-02') equals 1.0. It doesn't. It returns 1, an integer. If you need decimal precision, use CAST(DATEDIFF(ms, start, end) AS FLOAT) / 1000.0 / 86400.0 to convert milliseconds to fractional days.
Business applications rely on datediff sql server to track customer service response times. A support team might run:
SELECT DATEDIFF(hour, created_date, resolved_date) AS hours_to_resolve
FROM tickets
WHERE status = 'closed';
This query identifies cases where resolution took longer than four hours, flagging potential service issues.
Financial systems use it to calculate interest accrual periods. For example, a loan application may compute interest from the disbursement date to the current date using DATEDIFF(day, disbursement_date, GETDATE()).
Healthcare databases use it to monitor patient follow-up timelines. A clinic might flag patients whose appointment was scheduled more than 30 days ago but not yet attended:
SELECT patient_id
FROM appointments
WHERE DATEDIFF(day, scheduled_date, GETDATE()) >= 30
AND status != 'attended';
These queries show how datediff enables business logic based on time thresholds.
Many assume DATEDIFF returns floating-point numbers. It does not. Always cast to float if you need decimals. For example:
SELECT CAST(DATEDIFF(second, '2023-01-01 00:00:00', '2023-01-01 00:00:30') AS FLOAT) / 60.0;
-- Returns 0.5 (half a minute)
Another misconception is that DATEDIFF(month, '2023-01-31', '2023-02-28') returns 1. It does-but only because both dates are in different months. If you pass '2023-01-31' and '2023-02-28', the function still returns 1. But if you use day, it returns 28. This shows how unit choice affects output.
Some developers confuse DATEDIFF with DATEADD. While DATEADD adds a time interval to a date, DATEDIFF measures the gap. Using them together is common-for example, checking if a task deadline is within seven days:
SELECT *
FROM tasks
WHERE DATEDIFF(day, due_date, GETDATE()) <= 7;
One non-obvious fact: DATEDIFF respects the session's language and date format settings. If your server uses SET LANGUAGE British, DATEADD and DATEDIFF still interpret dates correctly-but only if the input string is unambiguous. Always use ISO 8601 format (YYYY-MM-DD) to avoid parsing errors.
I once debugged a report that showed "365 days" between two dates. The query used DATEDIFF(day, start, end). The dates were '2022-01-01' and '2023-01-01'. The result was 365. But the actual difference was 366 days because 2022 was not a leap year. Wait-no. 2024 is the next leap year. So 365 is correct. But the report still failed because the client expected 366. The error wasn't in datediff-it was in the assumption that all years have 365 days. That's why you must verify inputs and understand the calendar.
Another time, a stored procedure returned inconsistent results because the date variables were declared as VARCHAR(10). When the function parsed them, it interpreted '03/15/2023' as March 15 in US format, but the server was set to UK locale. The result was off by a month. Converting to DATETIME before passing to DATEDIFF fixed it.
SELECT
DATEDIFF(day, '2023-01-01', '2023-12-31') AS days,
DATEDIFF(month, '2023-01-01', '2023-12-31') AS months,
DATEDIFF(year, '2023-01-01', '2023-12-31') AS years;
Run it in the fiddle environment to see how each unit behaves. Try changing the start and end dates to observe edge cases.
Microsoft documentation confirms that DATEDIFF returns the number of interval boundaries crossed between two dates. This is consistent across SQL Server versions 2012 through 2022. The function is deterministic and safe for use in indexed views when combined with computed columns.
Use ISNULL or COALESCE to handle null values. A missing date causes DATEDIFF to return null. Always validate inputs in production code.
Final note: datediff sql server is not a replacement for DATEADD or CONVERT. It's a tool for measuring gaps. Combine it with other functions for full temporal analysis.