Dofactory.com
Dofactory.com
Earn income with your data and sql skills
Sign up and we'll send you the best freelance opportunities straight to your inbox.
We're building the largest freelancing marketplace for people like you.
By adding your name & email you agree to our terms, privacy and cookie policies.

SQL YEAR Function

YEAR returns the year from the specified date.

This function is equivalent to DATEPART(year, date).

Example

#

This example returns the year part from the specified date.

SELECT YEAR('12-18-2022 11:54:07') AS Year
Result:  1 record
Year
2022

Using YEAR

A common use is to get the current year.

SELECT YEAR(GETDATE()) as 'Current Year'
Result:  1 record
Current Year
2023

Syntax

Syntax of the YEAR function .

YEAR(date) 

date -- a date or datetime value.


More Examples

YEAR in WHERE

ORDER
Id
OrderDate
OrderNumber
CustomerId
TotalAmount
CUSTOMER
Id
FirstName
LastName
City
Country
Phone
Problem: List all orders for the year 2013.
SELECT FirstName, LastName, OrderNumber, 
       OrderDate, TotalAmount
  FROM [Order] O
  JOIN Customer C ON C.Id = O.CustomerId
 WHERE YEAR(OrderDate) = 2013
Result:  408 records
FirstName LastName OrderNumber OrderDate TotalAmount
Marias Anders 542773 2013-08-25 00:00:00.000 1086.00
Marias Anders 542822 2013-10-03 00:00:00.000 878.00
Marias Anders 542832 2013-10-13 00:00:00.000 330.00
Ana Trujillo 542889 2013-11-28 00:00:00.000 320.00
Ana Trujillo 542755 2013-08-08 00:00:00.000 479.75

YEAR in GROUP BY, ORDER BY

ORDER
Id
OrderDate
OrderNumber
CustomerId
TotalAmount
Problem: List the order count and total sales by year from latest to oldest.
SELECT YEAR(OrderDate) AS Year,
       COUNT(Id) AS Count, 
       SUM(TotalAmount) AS 'Total Sales'
  FROM [Order]
 GROUP BY YEAR(OrderDate)
 ORDER BY YEAR(OrderDate) DESC
Result:  3 records
Year Count Total Sales
2014 270 469771.34
2013 408 658388.75
2012 152 226298.50

You may also like



Last updated on Dec 21, 2023

Earn income with your data and sql skills
Sign up and we'll send you the best freelance opportunities straight to your inbox.
We're building the largest freelancing marketplace for people like you.
By adding your name & email you agree to our terms, privacy and cookie policies.