// dates & times reference

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.

類別
Dates & times
Returns
integer
In this category
6 of 121

語法

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.

引擎支援

引擎Support備註
SQL Server Different name or syntax DATEPART(year, ts) or YEAR(ts); no EXTRACT
PostgreSQL 是 Supported under this name.
MySQL 是 EXTRACT, plus YEAR(), MONTH(), DAY() shorthands
SQLite Different name or syntax strftime('%Y', ts) returns text; CAST it
Oracle 是 EXTRACT only; Oracle has no YEAR() or MONTH() function

範例

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;

小知識

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

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