In SQL Server, you can use the YEAR()
function to return the “year” part of a date. This is returned as an integer.
Below are examples of how to use this function.
Syntax
The syntax goes like this:
YEAR ( date )
Where date
is an expression that resolves to one of the following data types:
- date
- datetime
- datetimeoffset
- datetime2
- smalldatetime
- time
This can be a column expression, expression, string literal, or user-defined variable.
Example
Here’s a basic example of how it works:
SELECT SYSDATETIME() AS 'Date', YEAR(SYSDATETIME()) AS 'Year';
Result:
+-----------------------------+--------+ | Date | Year | |-----------------------------+--------| | 2018-06-18 00:49:51.0411540 | 2018 | +-----------------------------+--------+
So the YEAR()
function was able to extract the month from the datetime2 value (which was returned by the SYSDATETIME()
function).
Date Provided as a String Literal
Here’s an example where the date is provided as a string literal.
SELECT YEAR('2019-01-07') AS Result;
Result:
+----------+ | Result | |----------| | 2019 | +----------+
Example – Providing a Zero
Here’s what happens if you provide a zero for the date argument:
SELECT YEAR(0) AS Result;
Result:
+----------+ | Result | |----------| | 1900 | +----------+
The result is 1900
, which is the base year.
Similar Functions
You can also use the MONTH()
function to return the month from the date, and the DAY()
function to return the day.
There are also many different ways to format a date in SQL Server. For example, see How to Format the Date & Time in SQL Server.