SQL Server Tips

SQL DATEPART in SQL Server: Syntax, Every Datepart and the Index Gotcha

Updated December 4, 202615 min read

SQL DATEPART: get a part of a date. Scissors cut one calendar page into three separate blank cards.

How do you get the week number or the weekday out of a date in SQL Server?

Last month I had a column of order dates and a report that needed totals by week. I used SQL DATEPART to pull the week out. The numbers came back one week off from the finance sheet, and a year filter I added made the query crawl. Both turned out to be small things, so here is the short version.

The short answer: DATEPART(datepart, date) returns one part of a date as an int. DATEPART(week, '2025-03-14') returns 11 with the default SET DATEFIRST 7.

There are five ways to do this:

  1. My favorite: DATEPART (simplest): when I need one part of a date as a number
  2. ISO_WEEK: when the week number must match the ISO 8601 standard
  3. DATENAME: when I need the name, like Monday or March
  4. YEAR, MONTH and DAY: the same numbers as DATEPART, shorter to type
  5. A date range in WHERE (fastest): when I filter an indexed date column, I use a range, not DATEPART

I made test data so you can try these: jump to it. Two gotchas come after the scripts: week numbers that move, and a slow WHERE.

Get a part of a date with DATEPART in SQL

Use this when you need one part of a date as a number. The syntax is DATEPART(datepart, date). It returns an int.

T-SQL
DECLARE @d datetime2 = '2025-03-14 16:45:30';

SELECT
      DATEPART(year, @d)      AS [year]
    , DATEPART(quarter, @d)   AS [quarter]
    , DATEPART(month, @d)     AS [month]
    , DATEPART(dayofyear, @d) AS [dayofyear]
    , DATEPART(day, @d)       AS [day]
    , DATEPART(week, @d)      AS [week]
    , DATEPART(weekday, @d)   AS [weekday]
    , DATEPART(hour, @d)      AS [hour]
    , DATEPART(minute, @d)    AS [minute]
    , DATEPART(second, @d)    AS [second];

Result with the default US SET DATEFIRST 7:

yearquartermonthdayofyeardayweekweekdayhourminutesecond
2025137314116164530

I wrote these scripts for SQL 2022. The date can be a column, a variable or a string. It can be a date, datetime, datetimeoffset, datetime2, smalldatetime or time value. DATEPART works in SELECT, WHERE, HAVING, GROUP BY and ORDER BY. The datepart itself must be a keyword. A variable that holds the word year does not work.

Diagram of DATEPART returning ten values for the date 2025-03-14 16:45:30, from year 2025 to second 30
Figure 1: DATEPART returns one number per datepart for 2025-03-14 16:45:30 (default SET DATEFIRST 7).

Every datepart and what it returns

This table shows each datepart for '2007-10-30 12:15:32.1234567 +05:10' (a datetimeoffset(7) value). The values and abbreviations come from Microsoft's DATEPART page.

DatepartAbbreviationsReturns
yearyy, yyyy2007
quarterqq, q4
monthmm, m10
dayofyeardy, y303
daydd, d30
weekwk, ww44
weekdaydw3
hourhh12
minutemi, n15
secondss, s32
millisecondms123
microsecondmcs123456
nanosecondns123456700
tzoffsettz310 (minutes)
iso_weekisowk, isoww44

Gotcha: week and weekday change with SET DATEFIRST

week and weekday depend on SET DATEFIRST, which sets the first day of the week. The default for US English is 7 (Sunday). The default language of the login and SET LANGUAGE also affect the result. Check yours first:

T-SQL
SELECT @@DATEFIRST AS first_day_of_week;  -- 7 = Sunday, 1 = Monday

Here is what Microsoft shows for 2007-04-21 (a Saturday) under each setting:

SET DATEFIRSTweekweekday
1166
2175
3174
4173
5172
6171
7167

Week 1 always starts on January 1, whatever day that is. That is why week can reach 53 or even 54, and why the first and last weeks of a year can be short.

A note I left myself in a 2017 script shows how this bites. I built the Monday of the current week with one CASE branch per DATEPART(dw, ...) number. It only works when DATEFIRST is 7. On a server set to Monday-first, every branch is off by one day.

This version does not care about DATEFIRST. It turns the weekday into a Monday-first number (1 = Monday, 7 = Sunday), then steps back to the Monday:

T-SQL
DECLARE @d date = '2025-03-14';  -- a Friday

SELECT
      (DATEPART(weekday, @d) + @@DATEFIRST - 2) % 7 + 1 AS monday_first_weekday
    , DATEADD(day,
              1 - ((DATEPART(weekday, @d) + @@DATEFIRST - 2) % 7 + 1),
              @d) AS monday_of_that_week;
monday_first_weekdaymonday_of_that_week
52025-03-10

Check it worked: run it after SET DATEFIRST 1 and again after SET DATEFIRST 7. The result stays the same.

Get the ISO week with ISO_WEEK

Use this when the week number must match ISO 8601. ISO weeks start on Monday, and week 1 is the week that holds the year's first Thursday.

T-SQL
SET DATEFIRST 7;

SELECT d AS the_date
     , DATEPART(week, d)     AS [week]
     , DATEPART(iso_week, d) AS iso_week
FROM (VALUES (CAST('20100101' AS date))
           , (CAST('20120101' AS date))
           , (CAST('20121231' AS date))
           , (CAST('20151231' AS date))
           , (CAST('20241230' AS date))) AS v(d);
the_dateweekiso_week
2010-01-01153
2012-01-01152
2012-12-31531
2015-12-315353
2024-12-30531

January 1, 2010 is ISO week 53, because it belongs to the last week of 2009. December 30, 2024 is ISO week 1, because it belongs to the first week of 2025. The highest ISO week number in a year is 52 or 53.

Table comparing week and iso_week for five days around New Year 2025; the first two days are week 53 but ISO week 1
Figure 2: The same five days get different week and iso_week numbers (default SET DATEFIRST 7).

Get the name with DATENAME

Use this when you want text, like Friday or March. DATENAME takes the same arguments as DATEPART but returns text. DATEPART returns a number.

T-SQL
DECLARE @d datetime2 = '2025-03-14 16:45:30';

SELECT DATENAME(weekday, @d) AS day_name
     , DATENAME(month, @d)   AS month_name
     , DATEPART(month, @d)   AS month_number;
day_namemonth_namemonth_number
FridayMarch3

The names follow SET LANGUAGE, so a login set to another language gets other names. Sort by the number, not the name, or Friday lands before Monday.

Use YEAR, MONTH and DAY when you need only those three

YEAR(d), MONTH(d) and DAY(d) return the same values as DATEPART(year, d), DATEPART(month, d) and DATEPART(day, d). Use them when you want less typing.

I needUseReturns
A part as a numberDATEPARTint
A part as a nameDATENAMEtext
Year, month or day as a numberYEAR, MONTH, DAYint
Week, weekday, hour, minute, quarterDATEPARTint

Group by year and week, not by week alone

A week number is a plain int that restarts every January 1. If you group by week alone, week 5 of 2024 and week 5 of 2025 land in one row. Group by year and week together. Watch the year edge, too: the days around January 1 can fall into different weeks depending on which week system you use.

T-SQL
SELECT DATEPART(year, d) AS the_year
     , DATEPART(week, d) AS the_week
     , SUM(amount)       AS total
FROM (VALUES (CAST('20241230' AS date), 10)
           , (CAST('20241231' AS date), 20)
           , (CAST('20250101' AS date), 30)
           , (CAST('20250102' AS date), 40)
           , (CAST('20250107' AS date), 50)) AS v(d, amount)
GROUP BY DATEPART(year, d), DATEPART(week, d)
ORDER BY the_year, the_week;

With the default DATEFIRST 7, the Monday and Tuesday before January 1 end up in week 53 of 2024:

the_yearthe_weektotal
20245330
2025170
2025250

For ISO weeks, the year must be the ISO year. DATEPART(year, d) gives the wrong year for dates like December 30, 2024. This trick moves the date to the middle of its ISO year:

T-SQL
SELECT YEAR(DATEADD(day, 26 - DATEPART(iso_week, d), d)) AS iso_year
     , DATEPART(iso_week, d)                             AS iso_week
     , SUM(amount)                                       AS total
FROM (VALUES (CAST('20241230' AS date), 10)
           , (CAST('20241231' AS date), 20)
           , (CAST('20250101' AS date), 30)
           , (CAST('20250102' AS date), 40)
           , (CAST('20250107' AS date), 50)) AS v(d, amount)
GROUP BY YEAR(DATEADD(day, 26 - DATEPART(iso_week, d), d)), DATEPART(iso_week, d)
ORDER BY iso_year, iso_week;
iso_yeariso_weektotal
20251100
2025250

Gotcha: DATEPART in WHERE makes an indexed date column scan

DATEPART is fine in the SELECT list and in GROUP BY. In WHERE, on a column with an index, it is a problem: the query reads the whole index instead of jumping to the rows. It is easy to miss, because the query still returns the right rows.

Here is the slow way. It reads easily, and some tutorials show it:

T-SQL
-- Slow: the function hides OrderDate from the index
SELECT COUNT(*) AS orders, SUM(Amount) AS total
FROM dbo.Orders
WHERE DATEPART(year, OrderDate) = 2025
  AND DATEPART(month, OrderDate) = 3;

SQL Server has to run DATEPART on every row before it can compare. That makes the predicate non-sargable (it cannot use an index seek). For a longer look at sargable predicates, see our post on top SQL Server performance tuning mistakes, which covers them.

Here is the fix. Ask for a date range instead. Start at the first moment, and stop before the first moment of the next period:

T-SQL
-- Fast: a range on the bare column can use an index seek
SELECT COUNT(*) AS orders, SUM(Amount) AS total
FROM dbo.Orders
WHERE OrderDate >= '20250301'
  AND OrderDate <  '20250401';

Use >= with <, not BETWEEN with an end time like 23:59:59. A range with < never misses rows with fractions of a second.

A whole year works the same way: >= '20250101' AND < '20260101'. A single day: >= '20250314' AND < '20250315'.

When the period moves, work out the start date once and keep the column bare. This pulls the same month from last year:

T-SQL
DECLARE @start date = DATEFROMPARTS(YEAR(GETDATE()) - 1, MONTH(GETDATE()), 1);
DECLARE @end   date = DATEADD(month, 1, @start);

SELECT COUNT(*) AS orders, SUM(Amount) AS total
FROM dbo.Orders
WHERE OrderDate >= @start
  AND OrderDate <  @end;

Check it worked: run both queries with "Include Actual Execution Plan" on. The slow one should show an Index Scan on IX_Orders_OrderDate. The fast one should show an Index Seek on the same index. Both return the same numbers.

The fix does not fit every filter. "Every Monday" or "week 31 of any year" is not a range. The next section covers that case.

If the rewrite is not enough, or you find this pattern in dozens of queries, that is the kind of work Red9's senior DBAs do in SQL Server performance tuning: they find the bottleneck and document the before-and-after numbers for every change they make.

Index the part when you need it: computed column or calendar table

Use this when you filter on a part that is not a range.

A persisted computed column stores the part and lets you index it. MONTH, YEAR and DAY are always deterministic, which a persisted column needs. This example finds every December, across all years:

T-SQL
ALTER TABLE dbo.Orders ADD OrderMonth AS MONTH(OrderDate) PERSISTED;

CREATE INDEX IX_Orders_OrderMonth ON dbo.Orders (OrderMonth) INCLUDE (Amount);

SELECT COUNT(*) AS orders, SUM(Amount) AS total
FROM dbo.Orders
WHERE OrderMonth = 12;

The column makes every row bigger, so on a big table I test it first.

A calendar table holds one row per date with the parts already worked out. It is the better pick for week and weekday, because those depend on DATEFIRST. You set DATEFIRST once, when you fill the table:

T-SQL
SET DATEFIRST 7;

CREATE TABLE dbo.Calendar
(
      CalDate    date     NOT NULL PRIMARY KEY
    , CalYear    smallint NOT NULL
    , CalWeek    tinyint  NOT NULL
    , CalIsoWeek tinyint  NOT NULL
    , CalWeekday tinyint  NOT NULL
);

WITH d AS
(
    SELECT CAST('20230101' AS date) AS CalDate
    UNION ALL
    SELECT DATEADD(day, 1, CalDate) FROM d WHERE CalDate < '20251231'
)
INSERT dbo.Calendar (CalDate, CalYear, CalWeek, CalIsoWeek, CalWeekday)
SELECT CalDate, DATEPART(year, CalDate), DATEPART(week, CalDate)
     , DATEPART(iso_week, CalDate), DATEPART(weekday, CalDate)
FROM d
OPTION (MAXRECURSION 0);

-- Every Monday (weekday 2 when DATEFIRST is 7)
SELECT COUNT(*) AS orders, SUM(o.Amount) AS total
FROM dbo.Calendar AS c
JOIN dbo.Orders  AS o
  ON o.OrderDate >= c.CalDate
 AND o.OrderDate <  DATEADD(day, 1, c.CalDate)
WHERE c.CalWeekday = 2;

Gotcha: a missing part returns 1900 or an error

Ask a time value for a year and SQL Server has no year to give. With a string, it returns the default date, 1900-01-01:

T-SQL
SELECT DATEPART(year, '12:10:30.123')  AS y
     , DATEPART(month, '12:10:30.123') AS m
     , DATEPART(day, '12:10:30.123')   AS d;
ymd
190011

With a variable or a column, you get error 9810:

T-SQL
DECLARE @t time = '12:10:30.123';
SELECT DATEPART(year, @t);  -- error 9810

Check before you commit

  • Run SELECT @@DATEFIRST and decide if week and weekday are what you want.
  • Need ISO 8601 weeks? Use iso_week, and get the year with the 26 - iso_week trick.
  • Put the year in the GROUP BY next to the week.
  • Filter an indexed date column with >= and <, not DATEPART.
  • Read the plan: Index Seek, not Index Scan.

If the query still scans after the rewrite, look in the plan for a function that still wraps the column.

Try it on my test data

Run this once. It builds a 500,000-row table with orders spread over 2023 to 2025 and an index on the date. The dates are random, so your counts will differ from mine.

T-SQL
CREATE TABLE dbo.Orders
(
      OrderId   int IDENTITY(1,1) PRIMARY KEY
    , OrderDate datetime2(0)  NOT NULL
    , Amount    decimal(10,2) NOT NULL
);

CREATE INDEX IX_Orders_OrderDate ON dbo.Orders (OrderDate) INCLUDE (Amount);

INSERT dbo.Orders (OrderDate, Amount)
SELECT TOP (500000)
      DATEADD(SECOND, ABS(CHECKSUM(NEWID()) % 94694400), '20230101')
    , CAST(ABS(CHECKSUM(NEWID()) % 100000) AS decimal(10,2)) / 100
FROM sys.all_objects AS a
CROSS JOIN sys.all_objects AS b;

Check Red9's SQL Server Services

SQL Server Consulting

Perfect for one-time projects like SQL migrations or upgrades, and short-term fixes such as performance issues or SQL remediation.

Discover More ➜

SQL Server Managed Services

Continuous SQL support, proactive monitoring, and expert DBA help with one predictable monthly fee.

Discover More ➜

Emergency SQL Support

Take the stress out of emergencies with immediate access to a SQL Server Sr. DBA 24x7x365

Discover More ➜

Explore All Services ➜