SQL PRACTICE: SQL SERVER: DATEDIFF Function

 Q11. Find the age of employees from the provided table using SQL?


N.B: I am using the following:

Database: MSSQL

SQL Dialect: T-SQL 


Consider below table (Sql_data) as a source data.

select * from Sql_data;

Table 1. Source Data


-- Find the age of employees
select      empid, 
FirstName, 
LastName,
DOB, 
DATEDIFF(YY, DOB, GETDATE()) as Age
from Sql_data;

                                                                     Table 2. Age of Employees

Explanation: DATEDIFF function is used to return the date difference between two dates according to the date part specified (Year, Month, Day …..etc...). 

Syntax:
DATEDIFF(datepart, Date1, Date2)

Parameters:
datepart - Used to get the time difference between the two dates. It can be Year(YY, YYYY), Quarter(QQ, Q), month(MM,M), day(DD, D), …..etc.... In our case, we want to return the age in Year.
Date1 - the first date in operation. In our case, we are going to use the DOB column.
Date2 -  the second date we want to compare to the first date. In our case, we are going to use GETDATE() to get the current year.

DATEDIFF(YY, DOB, GETDATE()) as Age

Comments

Popular posts from this blog

SQL PRACTICE: SQL SERVER - DATEADD Function

SQL PRACTICE: SQL SERVER - Unique Records