Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

'In' operator in mySQL

Employee:

| id  | name  | department | managerId |
+-----+-------+------------+-----------+
| 101 | John  | A          | null      |
| 102 | Dan   | A          | 101       |
| 103 | James | A          | 101       |
| 104 | Amy   | A          | 101       |
| 105 | Anne  | A          | 101       |
| 106 | Ron   | B          | 101       |
+-----+-------+------------+-----------|

From the above Employee table, we need the names of managers who manages at least 5 employees.
I came up with this query:

select name from employee where managerid in (
    select managerid 
    from employee 
    where managerid is not null 
    group by managerid having count(*) > 4
);

I expected the following output:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

| name |
+------+
| John |
+------+

But instead, it throws up:

| ----- |
| Dan   |
| James |
| Amy   |
| Anne  |
| Ron   |

The where clause returns the managerid as 101. But the final select is not picking up the corresponding name. Where is this going wrong?

>Solution :

You are selecting all employees with a manager who has more than 4 employees. You need to change the where clause to filter by id instead of managerid:

select name from employee where id in (
    select managerid 
    from employee 
    where managerid is not null 
    group by managerid having count(*) > 4
);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading