SQL Exercises: Department where the employee works with ID 201
SQL SUBQUERY: Exercise-39 with Solution
From the following table, write a SQL query to find employees who work for the department in which employee ID 201 is employed. Return first name, last name, salary, and department ID.
Sample table: employees
SELECT first_name, last_name, salary, department_id FROM employees WHERE department_id = (SELECT department_id FROM employees WHERE employee_id = 201);
first_name last_name salary department_id Michael Hartstein 13000.00 20 Pat Fay 6000.00 20
The said query in SQL that retrieves the first name, last name, salary, and department id of all employees who belong to the same department as employee id 201.
The WHERE clause specifies that checking if the department_id of each employee matches the department_id of employee id 201. The condition uses a subquery in the WHERE clause to retrieve the department_id of employee id 201, and then compare it to the department_id of each employee.
SELECT e1.first_name, e1.last_name, e1.salary, e1.department_id FROM employees e1 JOIN employees e2 ON e1.department_id = e2.department_id WHERE e2.employee_id = 201;
SELECT first_name, last_name, salary, department_id FROM employees e1 WHERE EXISTS ( SELECT 1 FROM employees e2 WHERE e2.employee_id = 201 AND e1.department_id = e2.department_id );
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous Python Exercise: Location where department number 30 is located.
Next Python Exercise: Employee who works in that department which ID is 40.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends
- Python Interview Questions and Answers: Comprehensive Guide
- Scala Exercises, Practice, Solution
- Kotlin Exercises practice with solution
- MongoDB Exercises, Practice, Solution
- SQL Exercises, Practice, Solution - JOINS
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join