SQL – How to select current year from lookup table

The following SQL shows how to select a row from a table using the current year as the WHERE condition.

This is useful if you have a table of years and need to get the id corresponding to the current year, for example if you had the following table and needed to get the id of the current year:

Year_IDShort_Name
742016
762017
782018

This SQL query uses

  • GETDATE to get the current date
  • YEAR to turn the date into the year number (e.g. 2017)
  • CAST to convert the number to a string (which makes the comparison to the lookup table possible)

SELECT TOP 1 TY.Year_ID, TY.Short_Name 
FROM T_Years TY 
WHERE 
TY.Short_Name = CAST( YEAR(GETDATE() ) AS varchar(4) ) /* 2017 */

Was this article helpful?

Related Articles