// dates & times reference

SQL DATE_PART function

Returns one date field as double precision from a two-argument call: date_part('year', ts) gives the same value as EXTRACT(year FROM ts).

Categoria
Dates & times
Returns
double precision
In this category
46 of 121

Sintaxe

DATE_PART('year', ts)
DATE_PART('dow', d)
EXTRACT(year FROM ts)  -- standard equivalent

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

Suporte a mecanismos

MotorSupportNotas
SQL Server Different name or syntax DATEPART(year, ts) is the same idea, different argument order
PostgreSQL Sim Supported under this name.
MySQL Different name or syntax EXTRACT or the YEAR / MONTH shorthands
SQLite Different name or syntax strftime formats
Oracle Different name or syntax EXTRACT

Exemplos

PostgreSQL

SELECT date_part('year', created_at) AS yr FROM orders;

PostgreSQL

SELECT date_part('isodow', d) AS weekday FROM events;

PostgreSQL

SELECT CAST(date_part('hour', ts) AS int) AS hr FROM events;

Bom saber

  • date_part returns double precision; since PostgreSQL 14, EXTRACT returns numeric. The two can differ in the last digits of fractional seconds and epochs.
  • The field is a text argument, so it can come from a parameter or column: date_part($1, ts) works where EXTRACT needs the field written into the SQL.
  • It accepts the same fields as EXTRACT (dow, isodow, doy, epoch, isoyear); only the call shape and return type differ.

Questions about DATE_PART

Should I use date_part or EXTRACT?

EXTRACT. It is the standard, works on MySQL and Oracle too, and returns exact numeric on PostgreSQL 14+. date_part is useful when the field name is a parameter.

Why is date_part a double?

Fields like epoch and second carry fractions, and date_part predates the numeric return type EXTRACT got in PostgreSQL 14. Cast when you need integers.

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.