// dates & times reference

SQL YEAR function

Returns the calendar year as an integer, the standard GROUP BY key for per-year reporting on every engine.

카테고리
Dates & times
Returns
integer
In this category
37 of 121

구문

YEAR(d)
EXTRACT(year FROM d)
strftime('%Y', d)  -- SQLite, returns text

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

엔진 지원

엔진Support메모
SQL Server 예 Supported under this name.
PostgreSQL Different name or syntax EXTRACT(year FROM d) or date_part('year', d)
MySQL 예 Supported under this name.
SQLite Different name or syntax strftime('%Y', d) returns text; CAST it
Oracle Different name or syntax EXTRACT(year FROM d); there is no YEAR() function

예시

PostgreSQL

SELECT EXTRACT(year FROM created_at) AS yr FROM orders;

SQL Server

SELECT YEAR(created_at) AS yr FROM orders;

SQLite

SELECT CAST(strftime('%Y', created_at) AS INTEGER) AS yr FROM orders;

알아 두면 좋은 정보

  • SQLite's strftime returns text: GROUP BY works, but comparing to a number fails until you CAST the result to INTEGER.
  • PostgreSQL and Oracle have no YEAR() function (Oracle raises ORA-00904); use EXTRACT. SQL Server is the opposite: YEAR() works, EXTRACT does not exist.
  • WHERE YEAR(created_at) = 2024 cannot use an index on created_at; created_at >= '2024-01-01' AND created_at < '2025-01-01' can.

Questions about YEAR

Is YEAR(d) the same as EXTRACT(year FROM d)?

Yes, both return the calendar year. YEAR() is the shorthand SQL Server and MySQL accept; EXTRACT is the standard form used by PostgreSQL, MySQL and Oracle.

Why does my SQLite comparison return nothing?

strftime('%Y', d) yields text, so comparing to the number 2024 never matches. CAST(strftime('%Y', d) AS INTEGER) fixes it.

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

// 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.