First Day Of The Month In Sql Server

10 min read

Finding the first day of the month is one of the most common date manipulation tasks in SQL Server development. Whether you are building financial reports, partitioning data by time windows, or scheduling automated jobs, the ability to anchor a datetime value to the start of its month is a fundamental skill. SQL Server offers several approaches to achieve this, ranging from modern, readable functions to legacy techniques required for older compatibility levels. Understanding the nuances of each method—specifically regarding performance, data type handling, and version compatibility—ensures you write reliable, maintainable code But it adds up..

The Modern Standard: DATETRUNC (SQL Server 2022 and Later)

If you are running SQL Server 2022 (16.x) or Azure SQL Database, the introduction of the DATETRUNC function represents the most significant improvement in date handling in years. This function truncates a date or time value to the specified precision, effectively zeroing out the lower-level components Not complicated — just consistent..

To get the first day of the month, you simply specify month as the datepart Easy to understand, harder to ignore..

SELECT DATETRUNC(month, GETDATE()) AS FirstDayOfCurrentMonth;

Why this is the preferred approach:

  1. Readability: The intent is immediately clear to anyone reading the code.
  2. Data Type Preservation: DATETRUNC returns the same data type as the input. If you pass a datetime2(7), you get a datetime2(7) back with the time portion set to 00:00:00.0000000. If you pass a date, you get a date. This eliminates implicit conversion issues that plague older methods.
  3. Performance: It is optimized internally as a single scalar operation, avoiding the overhead of string conversion or complex arithmetic.
  4. Time Zone Awareness: It works naturally with datetimeoffset, preserving the offset while truncating the local time to the month boundary.

For developers on modern versions, this should be your default choice. It standardizes code and reduces the cognitive load required to decipher "date math" tricks.

The Classic Approach: DATEADD and DATEDIFF Arithmetic

For the vast majority of production environments still running SQL Server 2019 or earlier, the DATEADD / DATEDIFF pattern remains the gold standard for performance and reliability. This technique relies on integer arithmetic rather than string parsing, making it extremely fast and deterministic And that's really what it comes down to..

The logic calculates the number of month boundaries crossed since the "zero date" (January 1, 1900) and adds that number of months back to the zero date No workaround needed..

SELECT DATEADD(month, DATEDIFF(month, 0, GETDATE()), 0) AS FirstDayOfMonth;

Deconstructing the Logic

  1. DATEDIFF(month, 0, GETDATE()): Calculates the integer count of month boundaries between the base date (0, which is 1900-01-01) and the current date. For a date in October 2024, this returns roughly 1497.
  2. DATEADD(month, <that_integer>, 0): Adds that count of months back to the base date. Because the base date is the first day of a month, the result lands exactly on the first day of the target month at midnight (00:00:00.000).

Critical Nuance: The datetime Limitation

The literal 0 in T-SQL implicitly resolves to a datetime data type (precision 3.33ms). If your input column is datetime2, date, or datetimeoffset, this expression triggers an implicit conversion of your column to datetime before the calculation occurs.

This has two negative side effects:

  • Loss of Precision: datetime2(7) nanosecond precision is truncated to milliseconds.
  • Index Scans (Non-SARGable): If you use this in a WHERE clause against a datetime2 index (e.g., WHERE MyDateCol >= DATEADD(month, DATEDIFF(month, 0, GETDATE()), 0)), the implicit conversion on the column side (depending on precedence) or the mismatch in types can prevent index seeks, leading to scans.

The Fix for Modern Data Types: Cast the anchor 0 to the target data type explicitly.

-- For datetime2 columns
SELECT DATEADD(month, DATEDIFF(month, CAST('1900-01-01' AS datetime2), @MyDate), CAST('1900-01-01' AS datetime2));

-- For date columns (cleanest)
SELECT DATEADD(month, DATEDIFF(month, CAST('1900-01-01' AS date), @MyDate), CAST('1900-01-01' AS date));

Using CAST('1900-01-01' AS date) is often the cleanest anchor because the date type has no time component, guaranteeing the result is strictly the calendar day.

The EOMONTH Workaround (SQL Server 2012+)

Introduced in SQL Server 2012, EOMONTH returns the last day of the month. While it doesn't give you the first day directly, you can chain DATEADD to move one day forward from the previous month's end.

SELECT DATEADD(day, 1, EOMONTH(GETDATE(), -1)) AS FirstDayOfCurrentMonth;
  • EOMONTH(GETDATE(), -1) gets the last day of last month.
  • DATEADD(day, 1, ...) adds one day, landing on the 1st of the current month.

Pros: Highly readable; EOMONTH handles month-length logic (28/29/30/31 days) automatically. Cons: Requires two function calls. Like DATEADD/DATEDIFF, watch for data type precedence issues if passing datetime2 parameters, as EOMONTH returns the type of the input expression That's the whole idea..

The "String Formatting" Anti-Pattern (Avoid in Production)

You will frequently encounter legacy code using CONVERT or FORMAT to build a string representation of the first day, often relying on style codes like 112 (ISO yyyymmdd).

-- Common but discouraged for calculation logic
SELECT CONVERT(date, CONVERT(char(6), GETDATE(), 112) + '01');
-- Or using FORMAT (slowest)
SELECT FORMAT(GETDATE(), 'yyyy-MM-01');

Why you should avoid this for core logic:

  1. Performance: String allocation, parsing, and conversion are orders of magnitude slower than integer arithmetic. In a query processing millions of rows, this destroys CPU cycles.
  2. Implicit Conversion Risks: Relying on string-to-date conversion depends on session LANGUAGE and DATEFORMAT settings. While yyyymmdd (style 112) is generally safe (ISO 8601), concatenating '01' assumes the string parser interprets the result as YYYYMMDD.
  3. Non-SARGable: Wrapping a column in CONVERT or FORMAT inside a WHERE clause (WHERE CONVERT(...) = ...) guarantees an index scan.

Reserve string formatting strictly for the final presentation layer (reporting, JSON/XML output), never for filtering or joining.

Practical Application: SARGable Query Patterns

Practical Application: SARGable Query Patterns

When filtering by the first day of the month, the most common performance mistake is applying a date-truncation function to the column itself inside a WHERE clause Small thing, real impact..

-- Non-SARGable: forces an index scan
SELECT OrderID, OrderDate, TotalAmount
FROM Sales.Orders
WHERE DATEADD(month, DATEDIFF(month, 0, OrderDate), 0) = @TargetMonthStart;

SQL Server cannot use a standard B-tree index on OrderDate because the indexed value is transformed row-by-row before comparison. The optimizer must scan the entire table or index Easy to understand, harder to ignore..

To remain SARGable (Search ARGument Able), express the condition as a range against the raw column:

-- SARGable: enables an index seek
DECLARE @MonthStart date = DATEADD(month, DATEDIFF(month, 0, GETDATE()), 0);
DECLARE @MonthEnd date = DATEADD(month, 1, @MonthStart);

SELECT OrderID, OrderDate, TotalAmount
FROM Sales.Orders
WHERE OrderDate >= @MonthStart
  AND OrderDate < @MonthEnd;

By comparing the column directly to pre-calculated constants, the engine can seek to the first matching row and stop at the boundary. This pattern is especially critical for large fact tables where a scan versus a seek is the difference between milliseconds and minutes Still holds up..

If you frequently query by month, consider a persisted computed column or an indexed view that stores the truncated

month value, allowing the optimizer to seek directly on that precomputed key without runtime calculation Simple, but easy to overlook. But it adds up..

ALTER TABLE Sales.Orders ADD OrderMonthStart AS 
    DATEADD(month, DATEDIFF(month, 0, OrderDate), 0) PERSISTED;

CREATE INDEX IX_Orders_OrderMonthStart 
ON Sales.Orders(OrderMonthStart) 
INCLUDE (OrderID, TotalAmount);

With this index, filtering on OrderMonthStart = @MonthStart becomes a simple seek, and the included columns can satisfy the SELECT list without a key lookup.

For extremely large fact tables, table partitioning by month or a partitioned view can further reduce I/O by eliminating entire partitions outside the target range. Still, partitioning adds operational complexity and should be reserved for cases where simple indexing is insufficient.

Quick Reference: Do and Don't

Scenario Recommended Avoid
Get first of month DATEADD(month, DATEDIFF(month, 0, col), 0) String concatenation + CONVERT
Filter by month Range on raw column (>= and <) Function on column in WHERE
Display output FORMAT or CONVERT in

Most guides skip this. Don't.

the SELECT list only | Function on column in WHERE | | Compute month number | DATEDIFF(month, 0, col) | DATEPART + manual arithmetic on strings | | Month arithmetic (add/subtract) | DATEADD(month, n, col) | year * 12 + month integer math |

Handling Edge Cases

A few situations trip people up even after they have internalized the SARGable rule Easy to understand, harder to ignore. That alone is useful..

First, beware of the datetime versus date distinction. If your column is datetime and carries a time component, the half-open interval [ @MonthStart, @MonthEnd ) handles it correctly. Now, never use BETWEEN @MonthStart AND @MonthEnd when @MonthEnd is the first instant of the next month, because BETWEEN is inclusive and will double-count or leak boundary rows. The >= / < pair is the safest formulation regardless of the underlying type No workaround needed..

Worth pausing on this one.

Second, watch for parameters typed inconsistently with the column. Day to day, if OrderDate is a date but you pass a datetime2 parameter, or if types differ in precision, you can trigger an implicit conversion that quietly reintroduces a scan. Always match the parameter type to the column, or cast deliberately at the parameter boundary rather than around the column Easy to understand, harder to ignore..

-- Risky: implicit conversion between mismatched types
WHERE OrderDate = @MonthStart;   -- if @MonthStart is datetime and OrderDate is date

-- Safe: normalize the parameter, not the column
DECLARE @MonthStart date = CONVERT(date, @RawParam);
WHERE OrderDate >= @MonthStart AND OrderDate < @MonthEnd;

Third, consider the difference between local time and UTC. Because of that, a function like GETDATE() returns server-local time, whereas GETUTCDATE() returns UTC. If your data is stored in UTC, computing month boundaries from local time will shift the range by your offset and produce off-by-a-few-hours errors near month edges. Derive boundaries from the same clock the data was written with Simple, but easy to overlook..

Verifying the Seek

Do not take the plan on faith. Inspect the execution plan and confirm the operation against the date index is a Seek, not a Scan Simple, but easy to overlook..

SET STATISTICS IO, TIME ON;
GO

-- After running, check the plan for "Index Seek" and low logical reads

If you still see a scan after making the predicate SARGable, the usual culprits are a column-type mismatch, a function still wrapped around the column somewhere in the query, or stale statistics. Update statistics and re-examine before reaching for more aggressive options like partitioning.

Conclusion

The first day of the month is a deceptively simple value to compute and a surprisingly common source of performance problems. The core lesson is that how you express a filter matters as much as what you filter on. Wrapping the column in a function forces SQL Server to evaluate every row; expressing the same logic as a range over the raw column lets the engine seek straight to the data it needs.

The practical takeaways are straightforward: compute derived dates into variables once, filter with the half-open >= / < interval, match your types exactly, and confirm the plan shows a seek. When a single index is not enough, a persisted computed column or an indexed view can precompute the truncated value, and partitioning can prune whole segments at scale—but reach for those only after the simple, SARGable version has been ruled out Which is the point..

Quick note before moving on.

Master this one pattern and you will eliminate a large share of the avoidable scans that plague reporting and analytics workloads. The data is unchanged; only the way you ask for it gets faster Less friction, more output..

Latest Drops

Just In

Along the Same Lines

Explore the Neighborhood

Thank you for reading about First Day Of The Month In Sql Server. We hope the information has been useful. Feel free to contact us if you have any questions. See you next time — don't forget to bookmark!
⌂ Back to Home