Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

MySQL Subquery Exercises: Find the name of the employees who have a manager and worked in a USA based department

MySQL Subquery: Exercise-3 with Solution

Write a query to find the name (first_name, last_name) of the employees who have a manager and worked in a USA based department.

Sample table: employees


Sample table : departments


Sample table : locations


Code:

SELECT first_name, last_name FROM employees 
WHERE manager_id in (select employee_id 
FROM employees WHERE department_id 
IN (SELECT department_id FROM departments WHERE location_id 
IN (select location_id from locations where country_id='US')));

Explanation:

MySQL Subquery Syntax:

operand comparison_operator
operand IN (subquery)
operand comparison_operator SOME (subquery)

Where comparison_operator is one of these operators

=  >  <  >=  <=  <>  != 

and IN operator checks whether a value is within a set of values.

For example :

mysql> SELECT 2 IN (0,3,5,7);
        -> 0
mysql> SELECT 'wefwf' IN ('wee','wefwf','weg');
        -> 1

When used with a subquery, the word IN is an alias for = ANY. Thus, these two statements are the same:

SELECT s1 FROM t1 WHERE s1 = ANY (SELECT s1 FROM t2);
SELECT s1 FROM t1 WHERE s1 IN    (SELECT s1 FROM t2);

IN and = ANY are not synonyms when used with an expression list. IN can take an expression list, but = ANY cannot.

MySQL: Find the names of the employees who have a manager, works for a department based in United States

 

MySQL Code Editor:

Structure of 'hr' database :

hr database

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous:Write a query to find the name (first_name, last_name) of all employees who works in the IT department.
Next:Write a query to find the name (first_name, last_name) of the employees who are managers.

What is the difficulty level of this exercise?