SQL YEAR function
Returns the calendar year as an integer, the standard GROUP BY key for per-year reporting on every engine.
- Categoria
- Dates & times
- Returns
integer- In this category
- 37 of 121
Sintaxe
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.
Suporte a mecanismos
| Motor | Support | Notas |
|---|---|---|
| SQL Server | Sim | Supported under this name. |
| PostgreSQL | Different name or syntax | EXTRACT(year FROM d) or date_part('year', d) |
| MySQL | Sim | 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 |
Exemplos
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;
Bom saber
- 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.
Related on SQLly
- Get the first day of the month in SQL Server, PostgreSQL, MySQL, SQLite and Oracle Dialect comparison
- Count rows bucketed by time period Snippet
- Get the first and last day of the year in SQL Snippet
- Map a calendar date to a fiscal year in SQL Snippet
- Cumulative total by month Snippet
- Get the ISO week number of a date in SQL Snippet
Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, SQLite, Oracle.
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.