Function or operator · Text, numbers and dates

EXTRACT

EXTRACT gets one part of a date, such as the year or the month. SQLite and SQL Server use other functions for this.

EXTRACT example

PostgreSQL / MySQL
SELECT id,
       EXTRACT(YEAR FROM date) AS year
FROM orders
ORDER BY id;

In the course database every order is from May and June 2025, so year is 2025 in all 18 rows. The exact type returned by the function may vary between engines.

Check the result with small data

SQLite does not implement PostgreSQL's EXTRACT(YEAR FROM date) syntax.

Self-contained test · SQLite
SELECT CAST(strftime('%Y', '2026-10-11') AS INTEGER) AS year;
Check result
year
2026

In SQLite we use strftime to get the year and CAST to turn it into a number. The PostgreSQL equivalent would be EXTRACT(YEAR FROM DATE '2026-10-11').

Check your understanding: Which strftime format would you use to get the month in SQLite?

Show answer

'%m'. For example, strftime('%m', '2026-10-11') returns '10' as text; add CAST(... AS INTEGER) if you need a number.

How EXTRACT is used

The supported fields are not the same on every engine. Before using less common units, check your dialect's documentation.

What changes from case to case

SQLite does not implement the same call EXTRACT(... FROM ...). For an ISO date, strftime() can get the year, and you can then convert it to a number if needed.

SQLite
SELECT id,
       CAST(strftime('%Y', date) AS INTEGER) AS year
FROM orders
ORDER BY id;
Result verified in SQLite
idyear
12025
22026
32026
42026

Common mix-ups with EXTRACT

!
Copying EXTRACT into SQLite or DATEPART into PostgreSQL

The intent is the same, but the function differs. Keep the general concept separate from engine-specific syntax.

!
Cutting YYYY-MM-DD with SUBSTRING as a general rule

It can work with one specific text format, but it loses the date meaning and breaks if the type or format changes.