In PostgreSQL you can use the extract()
function to get the year from a date.
You can also use the date_part()
function to do the same thing.
Example 1: The extract() Function
Here’s an example of using the extract()
function to extract the year from a date.
SELECT extract( year from date '1974-12-16' ) AS "Year";
Result:
Year ------ 1974
Here’s another example using the current timestamp.
SELECT extract( year from current_timestamp ) AS "Year";
Result:
Year ------ 2020
Example 2: The date_part() Function
Here’s an example of using the date_part()
function instead.
SELECT date_part( 'year', date '1974-12-16' ) AS "Year";
Result:
Year ------ 1974
Note the slightly different syntax. Also the 'year'
parameter must be a string value (i.e. it’s enclosed in single quotes).
Example 3: ISO Year
You have the option of specifying the ISO 8601 week-numbering year.
Each ISO 8601 week-numbering year begins with the Monday of the week containing the 4th of January, so in early January or late December the ISO year may be different from the Gregorian year (depends on the year in question).
Here’s an example that demonstrates this.
SELECT extract( isoyear from date '2024-12-29' ) AS "2024-12-29", extract( isoyear from date '2024-12-30' ) AS "2024-12-30";
Result:
2024-12-29 | 2024-12-30 ------------+------------ 2024 | 2025
So both dates fall under 2024 in the Gregorian calendar, but they fall under a different ISO year.
The date_part()
function also accepts 'isoyear'
as an argument.