// SQL snippet

Get the ISO week number of a date in SQL

Weekly KPIs need week numbers, and the wrong week definition silently splits or merges weeks around New Year.

Main statement
SQL Server
다음도 지원
PostgreSQL MySQL Oracle

The task

DATEPART(ISO_WEEK, d) implements ISO 8601 week numbering, independent of DATEFIRST.

The snippet

Written for SQL Server. Versions for PostgreSQL, MySQL and Oracle are under Variations.

SQL Server
SELECT DATEPART(ISO_WEEK, d) AS iso_week,
       YEAR(DATEADD(DAY, 26 - DATEPART(ISO_WEEK, d), d)) AS iso_year
FROM (SELECT CAST('2027-01-01' AS DATE) AS d) x;

작동 방식

ISO_WEEK numbers weeks per ISO 8601: weeks begin on Monday and week 1 is the week containing the year's first Thursday. Plain DATEPART(WEEK) instead depends on DATEFIRST and can disagree. SQL Server has no ISO-year function, and YEAR(d) is wrong around New Year: 2027-01-01 is in ISO week 53 of 2026, and 2024-12-30 in week 1 of 2025. Shifting the date by 26 minus the week number moves it into the middle of its ISO year, so YEAR() of the shifted date is the ISO year.

Variations

PostgreSQL (WEEK is already ISO)

PostgreSQL
SELECT EXTRACT(WEEK FROM d) AS iso_week,
       EXTRACT(ISOYEAR FROM d) AS iso_year
FROM (SELECT DATE '2027-01-01' AS d) x;

MySQL

MySQL
SELECT WEEKOFYEAR(d) AS iso_week,
       YEARWEEK(d, 3) AS iso_yearweek
FROM (SELECT CURDATE() AS d) x;

Oracle

Oracle
SELECT TO_CHAR(d, 'IW') AS iso_week,
       TO_CHAR(d, 'IYYY') AS iso_year
FROM (SELECT DATE '2027-01-01' AS d FROM dual);

Questions that come up

Why does Jan 1 sometimes show week 52 or 53?

Under ISO rules, Jan 1 belongs to the previous year's last week when it falls on a Friday, Saturday or Sunday; 2027-01-01 is a Friday, so it is week 53 of 2026. That is why the ISO year (ISOYEAR, IYYY, YEARWEEK mode 3, or the shifted YEAR() on SQL Server) should be grouped with the week number, never the calendar year.

Keep reading

// snippets are better with a schema brain

Run these with autocomplete that knows your tables

SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.