// dates & times reference

SQL WEEK function

Returns the week number. PostgreSQL's EXTRACT(week) follows ISO-8601; the default week functions on SQL Server, MySQL, SQLite and Oracle do not.

Catégorie
Dates & times
Returns
integer
In this category
44 of 121

Syntaxe

EXTRACT(week FROM d)  -- PostgreSQL, ISO
DATEPART(iso_week, d)  -- SQL Server
WEEK(d, 3)  -- MySQL, ISO mode

Each block is a separate form. The support table and the examples show which engine takes which.

Prise en charge des moteurs

MoteurSupportNotes
SQL Server Different name or syntax DATEPART(week) follows DATEFIRST; ISO_WEEK is the ISO one
PostgreSQL Different name or syntax EXTRACT(week FROM d) is ISO
MySQL Oui WEEK(d) defaults to mode 0; WEEK(d, 3) or WEEKOFYEAR(d) for ISO
SQLite Different name or syntax %W is Monday-based; %U (Sunday-based) and the ISO %V arrived in SQLite 3.46
Oracle Different name or syntax TO_CHAR(d, 'WW') is not ISO; TO_CHAR(d, 'IW') is

Exemples

PostgreSQL

SELECT EXTRACT(isoyear FROM d) AS iso_yr,
       EXTRACT(week FROM d) AS iso_wk FROM events;

SQL Server

SELECT DATEPART(ISO_WEEK, d) AS iso_wk FROM events;

MySQL

SELECT WEEKOFYEAR(d) AS iso_wk FROM events;

SQLite

SELECT strftime('%G-%V', d) AS iso_wk FROM events;  -- SQLite 3.46+

Bon à savoir

  • ISO weeks start Monday and week 1 holds the year's first Thursday, so December 29 can be week 1 of next year and January 1 can be week 52 or 53 of the last.
  • SQL Server's DATEPART(week) counts January 1 as week 1 and shifts with DATEFIRST; DATEPART(iso_week) is the ISO-8601 answer.
  • MySQL's WEEK(d) uses default_week_format, which is 0 (Sunday start, weeks 0-53): WEEK('2024-12-30') is 52 while WEEK('2024-12-30', 3) and WEEKOFYEAR are 1.
  • Oracle's 'WW' just divides the year into 7-day blocks from January 1; 'IW' is the ISO spelling.

Questions about WEEK / ISO_WEEK

Why is my week number off by one?

Two systems coexist: ISO-8601 (Monday weeks, first-Thursday rule) and the US convention (Sunday weeks, January 1 starts week 1). Pick the ISO spelling your engine provides.

How do I group by ISO week-year?

Pair the ISO year with the ISO week: to_char(d, 'IYYY-IW') on PostgreSQL and Oracle, YEARWEEK(d, 3) on MySQL. SQL Server has no iso_year datepart; YEAR(DATEADD(day, 26 - DATEPART(iso_week, d), d)) computes it.

Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.

Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, SQLite, Oracle.

// fewer lookups

Functions your engine actually has

SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.