How to Get the Year from a Date in T-SQL
Database:
Operators:
Table of Contents
Problem:
You’d like to get the year from a date field in a SQL Server database.
Example:
Our database has a table named Children
with data in the columns Id
, FirstName
, LastName
, and BirthDate
.
Id | FirstName | LastName | BirthDate |
---|---|---|---|
1 | Jane | Smith | 2018-06-20 |
2 | Gary | Brown | 2010-02-02 |
3 | Lora | Adams | 2014-11-05 |
Let’s get the year from each child’s birthdate.
Solution:
We’ll use the YEAR()
function. Here’s the query you would write:
SELECT FirstName, LastName, YEAR (BirthDate) AS BirthYear FROM Children; |
Here’s the result of the query:
FirstName | LastName | BirthYear |
---|---|---|
Jane | Smith | 2018 |
Gary | Brown | 2010 |
Lora | Adams | 2014 |
Discussion:
Use SQL Server’s YEAR()
function if you want to get the year part from a date. This function takes only one argument – a date, in one of the date and time or date data types. (In our example, the column BirthDate
is a date data type). The argument can be a column name or an expression. (In our example, the argument is the BirthDate
column.)
The YEAR()
function returns an integer. For Jane Smith, it returns the integer 2018 from the birth date '2018-06-20'
.