// dates & times reference

SQL DAYOFYEAR function

Returns the ordinal day within the year, handy for seasonal comparisons like lining up April 10 across years without month arithmetic.

类别
Dates & times
Returns
integer
In this category
45 of 121

语法

DATEPART(dayofyear, d)  -- SQL Server
EXTRACT(doy FROM d)  -- PostgreSQL
DAYOFYEAR(d)  -- MySQL

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

引擎支持

引擎Support备注
SQL Server Different name or syntax DATEPART(dayofyear, d)
PostgreSQL Different name or syntax EXTRACT(doy FROM d)
MySQL 是 Supported under this name.
SQLite Different name or syntax strftime('%j', d) returns zero-padded text
Oracle Different name or syntax TO_CHAR(d, 'DDD') returns text

示例

PostgreSQL

SELECT EXTRACT(doy FROM created_at) AS doy FROM orders;

SQL Server

SELECT DATEPART(DAYOFYEAR, created_at) AS doy FROM orders;

MySQL

SELECT DAYOFYEAR(created_at) AS doy FROM orders;

值得了解

  • Leap years shift day numbers after February: day 60 is February 29 in 2024 and March 1 in 2023. Align years by date, not day number, when the range crosses February.
  • PostgreSQL spells it doy inside EXTRACT; the word dayofyear works on SQL Server and MySQL only.
  • SQLite and Oracle return zero-padded text ('DDD', '%j'); CAST to a number before arithmetic.

Questions about DAYOFYEAR

What is the difference between DAY and DAYOFYEAR?

DAY is 1-31 within the month; DAYOFYEAR is 1-366 within the year. MySQL's DAYOFMONTH and DAYOFYEAR names make the split explicit.

How do I convert a day-of-year back to a date?

MySQL: MAKEDATE(year, doy). SQL Server: DATEADD(day, doy - 1, DATEFROMPARTS(year, 1, 1)). Oracle: TO_DATE(year || LPAD(doy, 3, '0'), 'YYYYDDD').

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.