Dates and timesSQL standard

EXTRACT

Pulls a single part out of a date or time: the year, month, day, hour.

Syntax

EXTRACT(<field> FROM <date or time>)

Returns a number: YEAR — the year, MONTH — the month from 1 to 12, DAY — the day of the month, HOUR — the hour, DOW — the day of the week. The field is written without quotes. Handy for filtering or grouping by part of a date: orders before noon, sales by hour.

Data for the examples

orders

idcreated_atamount
12026-07-03 10:15:00120.50
22026-07-28 18:40:0080.25
32026-08-09 09:05:00199.99
42026-08-21 14:30:0045.00
52026-09-02 11:00:0064.75

These tables already exist in the sandbox — the examples below use them. Want to try this in your own database? Copy the SQL.

Year, month and day
SELECT EXTRACT(YEAR FROM TIMESTAMP '2026-09-13 15:47') AS year,
EXTRACT(MONTH FROM TIMESTAMP '2026-09-13 15:47') AS month,
EXTRACT(DAY FROM TIMESTAMP '2026-09-13 15:47') AS day;
yearmonthday
2026913
The month of each order
SELECT id, created_at,
EXTRACT(MONTH FROM created_at) AS month
FROM orders;
idcreated_atmonth
12026-07-03 10:15:007
22026-07-28 18:40:007
32026-08-09 09:05:008
42026-08-21 14:30:008
52026-09-02 11:00:009
Orders placed before noon
SELECT id, created_at
FROM orders
WHERE EXTRACT(HOUR FROM created_at) < 12;
idcreated_at
12026-07-03 10:15:00
32026-08-09 09:05:00
52026-09-02 11:00:00

Watch out

The result is a numeric, so seconds can have a fractional part: EXTRACT(SECOND FROM TIMESTAMP '2026-09-13 15:47:30.5') gives 30.500000.

DOW counts Sunday as 0 and Monday as 1. For the order where Monday is 1 and Sunday is 7, use ISODOW.

Grouping by EXTRACT(MONTH FROM …) merges the same month of different years into one row. For monthly reports, use DATE_TRUNC('month', …).

Learn more in the course