In SQL Server, why do DATEDIFF and EOMONTH-based month filters give wrong answers, and how do you write them correctly?
answer
- counting, not measuring
- boundaries crossed, not time elapsed
- what type EOMONTH returns
- datetime rounds .999 upward
- half-open range with DATEADD
basics
~20 sDATEDIFF counts datepart boundaries crossed, so one second across New Year is a year. EOMONTH returns a date, so <= EOMONTH(...) drops the last day's later times. Filter months as half-open ranges: >= first day and < DATEADD(month, 1, first day).
solid answer
~40 s`DATEDIFF(datepart, start, end)` returns the number of `datepart` **boundaries crossed**, not elapsed time: `DATEDIFF(year, '2025-12-31', '2026-01-01')` is `1`, so it misstates ages and durations unless you correct for it. It returns `int` and raises Msg 535 on overflow at fine dateparts, which is what `DATEDIFF_BIG` is for. `EOMONTH(date [, months])` returns a **`date`**, so `created_at <= EOMONTH(@d)` on a `datetime2` column compares against midnight and silently drops the last day after 00:00. Hard-coding `'... 23:59:59.999'` fails too on a `datetime` column, because `datetime` rounds to `.000`, `.003` or `.007` and that literal rounds up to the next day. The robust month filter is half-open: `created_at >= @month_start AND created_at < DATEADD(month, 1, @month_start)`.
go deeper
Recall the four functions and their argument order, and that DATEDIFF counts boundaries crossed rather than elapsed time.
Explain why EOMONTH's date return type and datetime's rounding break inclusive month ranges, and write the half-open range that replaces them.
Show you catch these in review: off-by-one ages, Msg 535 overflows at fine dateparts, and week numbers that change with the session's language.
Speak to standards: half-open ranges, datetime2 in new tables and ISO weeks in reports remove a class of reporting bugs across every team.
## The setting: porting a monthly report A reporting query written for another engine uses `EXTRACT`, interval arithmetic and a "between first and last day" filter. In SQL Server you rewrite it with **`DATEADD`**, **`DATEDIFF`**, **`DATEPART`** and **`EOMONTH`**, and each has one behaviour that produces numbers that look right and are not. ## DATEDIFF counts boundaries, not elapsed time `DATEDIFF(datepart, startdate, enddate)` returns, as a signed **`int`**, the number of **`datepart` boundaries crossed** between the two values. It does not measure a duration and round it. - `DATEDIFF(year, '2025-12-31', '2026-01-01')` returns `1`: one year boundary lies between them, although one day passed. - `DATEDIFF(day, '2026-03-01 23:59', '2026-03-02 00:01')` returns `1` after two minutes. - `DATEDIFF(month, '2026-01-31', '2026-02-01')` returns `1`. So `DATEDIFF(year, birth_date, @today)` overstates a person's age by one until their birthday in the current year. A common correction subtracts one when the anniversary has not been reached: ```sql DATEDIFF(year, birth_date, @today) - CASE WHEN DATEADD(year, DATEDIFF(year, birth_date, @today), birth_date) > @today THEN 1 ELSE 0 END ``` Two more rules matter in production: 1. The result is an `int`, so a fine `datepart` over a wide range overflows with **Msg 535**. For `millisecond` the documented maximum span is about 24 days, and for `second` about 68 years. **`DATEDIFF_BIG`** returns `bigint` for these cases. 2. For `week`, two dates in different years but the same calendar week return `0`. ## EOMONTH returns a date `EOMONTH(start_date [, month_to_add])` returns the last day of the month containing `start_date`, after adding `month_to_add` months if you pass it. Its return type is **`date`**, with no time part. Comparing a `datetime2` column to it converts that `date` to midnight, so: - `created_at <= EOMONTH('2026-01-15')` keeps rows up to `2026-01-31 00:00:00` and **drops the rest of 31 January**; - `created_at BETWEEN '2026-01-01' AND EOMONTH('2026-01-01')` has the same hole. The fix is to stop asking for the "last moment" of a month at all and use a **half-open range**: ```sql WHERE created_at >= @month_start AND created_at < DATEADD(month, 1, @month_start) ``` `@month_start` can come from `DATEFROMPARTS(YEAR(@d), MONTH(@d), 1)` or `DATEADD(day, 1, EOMONTH(@d, -1))`. The range works for `date`, `datetime` and `datetime2` alike, and it leaves the column bare, so an index on `created_at` can still be used for a seek. ## Why '23:59:59.999' is not the end of the day **`datetime`** is accurate only to increments of `.000`, `.003` or `.007` seconds, and a value is rounded to the nearest increment. `'2026-01-31 23:59:59.999'` therefore rounds up to `2026-02-01 00:00:00.000`, and a `BETWEEN` on a `datetime` column that ends there **includes** rows stamped at midnight on 1 February. **`datetime2`** has 100-nanosecond accuracy and no such rounding, which is one reason new schemas use it, but the half-open range is still the safer habit because it never depends on the precision. ## DATEADD and DATEPART edge cases | Expression | Result | Why | |---|---|---| | `DATEADD(month, 1, '2024-08-31')` | `2024-09-30 00:00:00.000` | the day is clamped to the last day of the target month | | `DATEADD(month, 1, CAST('2024-01-31' AS date))` | `2024-02-29` | 2024 is a leap year | | `DATEADD(day, 1, '2026-01-01')` | a `datetime` | a string literal input returns `datetime` | | `DATEPART(week, @d)` | depends on `SET DATEFIRST` | the session's first day of the week | | `DATEPART(iso_week, @d)` | ISO 8601 week number | weeks start Monday; week 1 holds the first Thursday | Notes on these: - `DATEADD` returns the same type as a typed input but **`datetime` for a string literal**, and it raises an error when a string literal's seconds carry more than three decimal places, so `DATEADD(day, 1, '2026-01-01 10:00:00.1234567')` fails; cast the literal to `datetime2` first. - `DATEPART(week, ...)` and `DATEPART(weekday, ...)` follow `DATEFIRST`, which defaults to `7` (Sunday) for U.S. English and changes with the session's language, as `SET LANGUAGE` shows. Use `iso_week` for week numbers in a European report. ## A checklist for the ported report - Replace every "last day 23:59:59" bound with a half-open range. - Check every `DATEDIFF` whose caller expects elapsed whole units. - Keep date columns `datetime2` or `date` rather than `datetime` in new tables. - Avoid `YEAR(col) = 2026` style filters on large tables; they hide the column from an index seek.
- How do you get the first day of the month containing @d in SQL Server?Two common forms: `DATEFROMPARTS(YEAR(@d), MONTH(@d), 1)`, which builds a `date` from parts, or `DATEADD(day, 1, EOMONTH(@d, -1))`, which takes the last day of the previous month and adds one day. Both return a `date`, which is what you want as the inclusive lower bound of a half-open range.
- What does DATEDIFF(millisecond, @start, @end) do when the two values are 30 days apart?It raises Msg 535, because the count of millisecond boundaries no longer fits in `int`; the documented maximum span for `millisecond` is about 24 days and 20 hours. Use `DATEDIFF_BIG`, which returns `bigint`, or a coarser `datepart` such as `second`.
DATEDIFF is like counting how many New Year's midnights you lived through rather than how many full years passed: someone born one second before midnight on 31 December has crossed one after two seconds.
- DATEDIFF(year, a, b) returns the number of full years elapsed.
- EOMONTH returns the last moment of the month, including time.
- Ending a datetime range at 23:59:59.999 captures the whole last day.
- DATEADD(month, 1, '2024-01-31') overflows into March.
- DATEPART(week, d) returns the same number on every server.