Write a query to find employees hired between two specific dates
Great! Let’s now extend the previous example to include a query that finds employees hired between two specific dates, and I’ll explain every step in detail — including creating the table, inserting dummy data, and writing the SQL query with output.
Task:
Write a query to find employees hired between two specific dates.
Step 1: Create the employees table
CREATE TABLE employees (
id INT PRIMARY KEY,
name VARCHAR(100),
department VARCHAR(50),
salary DECIMAL(10,2),
hire_date DATE
);
Step 2: Insert Dummy Data
INSERT INTO employees (id, name, department, salary, hire_date) VALUES
(1, 'John Smith', 'HR', 50000.00, '2020-01-15'),
(2, 'Alice Johnson', 'Engineering', 75000.00, '2019-03-22'),
(3, 'Bob Lee', 'Sales', 62000.00, '2021-07-10'),
(4, 'Mary Jane', 'Engineering', 80000.00, '2018-11-05'),
(5, 'Tom Hardy', 'Marketing', 55000.00, '2022-06-01');
Step 3: Write the Query to Filter by Date Range
Suppose we want to find all employees hired between '2019-01-01' and '2021-12-31', then we use the BETWEEN operator on the hire_date column:
SELECT * FROM employees
WHERE hire_date BETWEEN '2019-01-01' AND '2021-12-31';
Explanation:
BETWEENis inclusive, so it includes employees hired on the start and end dates.- This query returns employees whose
hire_dateis between 2019-01-01 and 2021-12-31.
Step 4: Expected Output
| id | name | department | salary | hire_date |
|---|---|---|---|---|
| 1 | John Smith | HR | 50000.00 | 2020-01-15 |
| 2 | Alice Johnson | Engineering | 75000.00 | 2019-03-22 |
| 3 | Bob Lee | Sales | 62000.00 | 2021-07-10 |
Bonus: Use >= and <= Instead of BETWEEN
Alternatively, you can write:
SELECT * FROM employees
WHERE hire_date >= '2019-01-01' AND hire_date <= '2021-12-31';
It gives the same result as BETWEEN.
Summary
| Task | SQL |
|---|---|
| Create Table | CREATE TABLE employees (...) |
| Insert Data | INSERT INTO employees VALUES (...) |
| Query Between Dates | SELECT * FROM employees WHERE hire_date BETWEEN 'start_date' AND 'end_date'; |
Your Feedback
Help us improve by sharing your thoughts
Online Learner helps developers master programming, database concepts, interview preparation, and real-world implementation through structured learning paths.
Quick Links
© 2023 - 2026 OnlineLearner.in | All Rights Reserved.
