SQL Standard

How to Extract the Year from a Date in SQL

This article will discuss how you can extract the year from a date string using functions from Standard SQL and extended functions.

SQL Extract Function

You can extract the year using the extract() function in standard SQL. The function takes date or DateTime objects and returns the year as a string.

The function syntax is expressed as shown below:

EXTRACT(part FROM date_expression);

The function is effortless and accepts a date as a literal value or an expression that returns a date object.

Below is an example on how to extract the year from March 21st 2022.

SELECT EXTRACT(YEAR FROM DATE '2022-02-21') AS year;

Note the example above uses the date literal to extract the year. The query above should return as:

year
------
2022

You can also pass an expression that returns the date to the extract function. For example, the code below gives the now function as the argument to the extract function.

SELECT EXTRACT(YEAR FROM CURRENT_DATE) AS year;

Here, the query above should return the year as ‘2022’ as shown:

year
------
2022

NOTE: The extract() method is part of standard SQL and is supported by major database engines such as MySQL, PostgreSQL, and Oracle.

However, in SQL Server, this function is renamed to YEAR or DATEPART. This will depend on the version of the SQL Server you are running.

SQL Year Function

This function accepts the date as a literal string or an expression and extracts the year part of the date.

Example usage is as shown below:

SELECT YEAR(CURRENT_TIMESTAMP);

The above returns “2022” as we expected.

SQL Datepart Function

You can also use the datepart function to get the year from a date. This function feels closely similar to the extract function in Standard SQL.

An example usage is as shown:

SELECT DATEPART(YEAR, CURRENT_TIMESTAMP) as year;

The above query should return:

year
------
2022
(1 row)

Conclusion

This article covers two main methods to extract the year from a date. Keep in mind that various database engines may implement extended functionality. Learn more through our website.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list