﻿ SQL - Department where the employee works with ID 201

# 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

Sample Solution:

SELECT first_name, last_name, salary, department_id
FROM employees
WHERE department_id =
(SELECT department_id
FROM employees
WHERE employee_id = 201);

Sample Output:

first_name	last_name	salary	department_id
Michael		Hartstein	13000.00	20
Pat		Fay		6000.00		20

Code Explanation:

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.

Visual Presentation:

Alternative Solutions:

Using JOIN:

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;

Using EXISTS:

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
);

## Query Visualization:

Duration:

Rows:

Cost:

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.

﻿