Forum

Write an SQL Query ...
 
Share:
Notifications
Clear all

Write an SQL Query to Find Employees Who Joined in the Last 6 Months


Posts: 71
Guest
Topic starter
(@Vinay Kumar)
Trusted Member
Joined: 4 years ago

How can you write an SQL query to find employees who joined within the last 6 months? Assume you have an employees table with columns employee_id, employee_name, and joining_date.

Answer:

To find employees who joined within the last 6 months, we can use the DATEADD() or INTERVAL function (depending on the SQL database) to calculate a date range. Here’s how to achieve this in SQL.

Solution: Using DATEADD or INTERVAL

Assume the employees table structure is as follows:

employee_id employee_name joining_date
1 Alice 2024-01-15
2 Bob 2024-05-20
3 Charlie 2023-11-10
4 David 2024-04-10
5 Eve 2023-10-25

We want to find employees whose joining_date is within the last 6 months from the current date.

SQL Query (using DATEADD in SQL Server):

sql
 
SELECT employee_id, employee_name, joining_date
FROM employees
WHERE joining_date >= DATEADD(month, -6, GETDATE());

SQL Query (using INTERVAL in MySQL):

sql
 
SELECT employee_id, employee_name, joining_date
FROM employees
WHERE joining_date >= DATE_SUB(CURDATE(), INTERVAL 6 MONTH);

Explanation:

  1. DATEADD or DATE_SUB Function: These functions allow us to subtract 6 months from the current date (GETDATE() in SQL Server or CURDATE() in MySQL).
  2. Filtering Condition: The WHERE joining_date >= ... clause filters only employees who joined on or after the calculated date, which is 6 months before today’s date.

Expected Output:

Based on the example data, if today’s date is assumed to be 2024-11-01, the result would look like:

employee_id employee_name joining_date
2 Bob 2024-05-20
4 David 2024-04-10

Solution for Databases without DATEADD or DATE_SUB

In databases that don’t support DATEADD or DATE_SUB, we can calculate the past date manually using the year and month functions.

For instance, if the database allows date arithmetic:

sql
 
SELECT employee_id, employee_name, joining_date
FROM employees
WHERE joining_date >= CURRENT_DATE - INTERVAL '6 months';

Leave a reply

Author Name

Author Email

Title *

 
Preview 0 Revisions Saved
Share: