SQL EXTRACT function
Returns one field of a date or timestamp as a number: the year of an order, the hour of a login. EXTRACT is the standard form; SQL Server and SQLite use their own functions.
- Catégorie
- Dates & times
- Returns
integer- In this category
- 6 of 121
Syntaxe
EXTRACT(year FROM ts)
DATEPART(year, ts) -- SQL Server
Each block is a separate form. The support table and the examples show which engine takes which.
Prise en charge des moteurs
| Moteur | Support | Notes |
|---|---|---|
| SQL Server | Different name or syntax | DATEPART(year, ts) or YEAR(ts); no EXTRACT |
| PostgreSQL | Oui | Supported under this name. |
| MySQL | Oui | EXTRACT, plus YEAR(), MONTH(), DAY() shorthands |
| SQLite | Different name or syntax | strftime('%Y', ts) returns text; CAST it |
| Oracle | Oui | EXTRACT only; Oracle has no YEAR() or MONTH() function |
Exemples
PostgreSQL
-- same on MySQL and Oracle SELECT EXTRACT(year FROM created_at) AS yr FROM orders;
SQL Server
SELECT DATEPART(year, created_at) AS yr FROM orders;
SQLite
SELECT CAST(strftime('%Y', created_at) AS INTEGER) AS yr FROM orders;
Bon à savoir
- SQLite's strftime returns text: strftime('%Y', ts) = 2026 compares text with a number and is false. CAST the result to INTEGER first.
- Week numbers: EXTRACT(week) on PostgreSQL is the ISO week, matching SQL Server's DATEPART(iso_week). SQL Server's DATEPART(week) counts from January 1 and follows DATEFIRST, so the two disagree near year boundaries.
- SQL Server and MySQL also have YEAR(d), MONTH(d) and DAY(d) shorthands. Oracle does not: YEAR(SYSDATE) fails with ORA-00904.
- On Oracle, EXTRACT(hour FROM ...) only works on TIMESTAMP values, not DATE; cast first or use TO_CHAR(d, 'HH24').
Questions about EXTRACT / DATEPART
What is the difference between EXTRACT and DATEPART?
EXTRACT is the SQL standard (PostgreSQL, MySQL, Oracle); DATEPART is SQL Server's spelling with comma syntax. They cover the same parts, though week numbering differs as described above.
Does SQLite have EXTRACT?
No. strftime('%Y', ts) is the stand-in, and it returns text. CAST the result to INTEGER before comparing or doing arithmetic.
Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.
Related on SQLly
- Get the Unix timestamp of a date in SQL Server, PostgreSQL, MySQL, SQLite and Oracle Dialect comparison
- Map a calendar date to a fiscal year in SQL Snippet
- Get the ISO week number of a date in SQL Snippet
- Add N business days to a date in SQL Snippet
- Compute age in years, months and days in SQL Snippet
- Count rows bucketed by time period Snippet
Cheat sheets for the engines that have it: SQL Server, MySQL, PostgreSQL, 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.