How to Find Employees Who were Hired in the Last n Months in SQL Server

← PrevNext →

Using DATEADD() function. Yes, its an in-built function in SQL Server, which will help you find the employees who have been hired in the last n months. The n in this case can be any number. Let’s see some examples.

Create a Table in SQL Server

This is my employee table with few rows in it.

Sample Employee Table

Or, you can use this sample Employee table. Create the table.

Find Employees Hired in the Last n Months

Here’s the query.

DECLARE @n INT
SET @n = 3
SELECT * FROM Employees
WHERE DOJ >= DATEADD(M, -@n, GETDATE())

I am using a variable to define the number of months, since its n months. So, the value can be anything like 3, 4, 6 etc.

This is more dynamic and you can execute this query using a Stored Procedure, if it’s a repeated process.

Here’s the output. (Assuming it’s the month of May)

Employees who were Hired in the last n Months

Find the Employees who have been Hired in the Last 4 Months

Well, you can even use this query, if you know the number of months.

SELECT *FROM Employees
WHERE DOJ >= DATEADD(MONTH, -4, GETDATE())

Now, let’s understand the SQL function, which is responsible for this output.

DATEADD() function

The DATEADD() function returns a date time (smalldatetime). Its syntax is,

DATEDADD(interval, increment (int), expression (date))

Note: The DATEADD() function is also supported by Azure SQL Database.

← PreviousNext →