Problem Statement
Table: Employee
Each row in this table represents an individual employee, detailing their unique ID, name, and the department ID they belong to.
+---------------+---------+
| Column Name | Type |
+---------------+---------+
| id | int |
| name | varchar |
| department_id | int |
+---------------+---------+
id is the primary key for this table.
department_id refers to the ID of the department the employee works in.Develop a solution to find the names of employees who do not work in a department with id = 3. The output should be sorted in any order.
Example
Input:
Employee table:
+----+-------+--------------+
| id | name | department_id|
+----+-------+--------------+
| 1 | Alice | 1 |
| 2 | Bob | 3 |
| 3 | Cindy | 2 |
| 4 | Dave | 3 |
| 5 | Eve | 1 |
+----+-------+--------------+Output:
+-------+
| name |
+-------+
| Alice |
| Cindy |
| Eve |
+-------+In this example, Alice, Cindy, and Eve do not work in department where id = 3.
Try It Yourself
Database Exercise
Database Schema:
-- Database schema would be rendered hereExercise Script:
-- Exercise script would be rendered hereAvailable actions: Execute
Solution
To solve this problem, we need to identify employees in the Employee table who are not part of a specified department (id = 3). SQL queries will be utilized to filter and retrieve the necessary data.
- Select Employee Names: Begin by executing a
SELECTstatement to fetch thenamecolumn from theEmployeetable. - Exclude Specific Department: Introduce a
WHEREclause to filter out employees associated with the departmentid = 3.
SQL Query
The definitive SQL query is as follows:
SELECT name
FROM Employee
WHERE department_id <> 3;Step by Step Approach
Step 1: Select Employee Names
Initiate the process by selecting the name from the Employee table, which forms the essence of our output.
SELECT name
FROM EmployeeOutput After Step 1:
+-------+
| name |
+-------+
| Alice |
| Bob |
| Cindy |
| Dave |
| Eve |
+-------+Step 2: Exclude Specific Department
Refine the selection by applying a condition to exclude employees from department id = 3.
SELECT name
FROM Employee
WHERE department_id <> 3Final Output:
+-------+
| name |
+-------+
| Alice |
| Cindy |
| Eve |
+-------+