SQL EXTRACT

Pulls a single named part — year, month, day, and more — out of a date or timestamp, returning it as a plain number.

What & Why

EXTRACT(field FROM source) pulls one specific component out of a date or timestamp value and returns it as a number. The next several lessons cover each individual field (year, quarter, month, week, day, day of week, hour) one at a time — this lesson is about the general syntax they all share.

See How It Works

BUSINESS QUESTION

Marketing wants the signup year, month, and day shown beside every lead's original created_at value.

idcampaign_idemailcreated_atqualified_atconverted_atlead_scoresourcecountry
3011ana@example.com2024-01-21 09:10:00+002024-01-22 11:00:00+002024-02-02 10:00:00+0086google_adsUS
3021ben@example.com2024-01-24 12:40:00+00NULLNULL52google_adsCA
3032chloe@example.com2024-02-16 08:30:00+002024-02-18 14:20:00+00NULL74emailGB
3043dev@example.com2024-03-20 17:15:00+002024-03-21 09:00:00+002024-04-04 16:00:00+0091linkedinUS
Watch the same timestamps expose three calendar fieldsStep 1 of 3
EXTRACT(YEAR FROM created_at)
idcreated_atsignup_year
3012024-01-21 09:10:00+002024
3022024-01-24 12:40:00+002024
3032024-02-16 08:30:00+002024
3042024-03-20 17:15:00+002024

YEAR returns 2024 for each displayed lead while the original timestamp remains visible.

EXAMPLE QUERY
SELECT
  id,
  created_at,
  EXTRACT(YEAR FROM created_at)::int AS signup_year,
  EXTRACT(MONTH FROM created_at)::int AS signup_month,
  EXTRACT(DAY FROM created_at)::int AS signup_day
FROM marketing.leads
ORDER BY created_at, id;
Now You Try

Practice this concept

Marketing wants signup year, month, and day beside every lead created_at value.

Available schema
marketing

Prefix tables with marketing.table_name.

idcreated_atsignup_yearsignup_monthsignup_day
marketing.leads
ColumnType
idinteger
campaign_idinteger
emailtext
created_attimestamp with time zone
qualified_attimestamp with time zone
converted_attimestamp with time zone
lead_scoreinteger
sourcetext
countrytext
archive_statustext
query.sql
Intermediate business practice

Sign up free to try it on a real business scenario