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:
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.
Note the example above uses the date literal to extract the year. The query above should return as:
------
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.
Here, the query above should return the year as ‘2022’ as shown:
------
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:
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:
The above query should return:
------
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.