adrenaline245
adrenaline245

Reputation: 53

SELECT values of a column that are not in another column in the same table MySQL

I have a sample table called "Quant1" as follows (ID - int PK, Name - Varchar(45), Salary - float, manager_id - int):

ID Name Salary Manager_id
1 John 300 3
2 Mike 200 3
3 Sally 550 4
4 Jane 500 7
5 Joe 600 7
6 Dan 600 3
7 Phil 550 NULL

I want to list employees not managing anyone, i.e. ID 1,2,5,6.So I write the following code:

SELECT *
FROM quant1
WHERE id NOT IN 
    (SELECT DISTINCT manager_id
    FROM quant1);

But it doesn't result in the desired outcome. Can anyone spot the error in my script? Thanks in advance!

Upvotes: 2

Views: 2659

Answers (3)

sharma ji
sharma ji

Reputation: 1

This query will return all the rows from the table_name table where the column_name column is not contained in the column_name column from the table_name table.

SELECT * FROM table_name 
WHERE column_name NOT IN 
(
 SELECT column_name FROM table_name
)

Upvotes: 0

Aakash Yadav
Aakash Yadav

Reputation: 84

SELECT *
FROM quant1
WHERE id NOT IN 
    (SELECT DISTINCT manager_id
    FROM quant1 WHERE manager_id IS NOT NULL);

Upvotes: 0

Barmar
Barmar

Reputation: 780688

You have to exclude the NULL manager ID from the subquery, because all comparisons with NULL fail.

SELECT *
FROM quant1
WHERE id NOT IN 
    (SELECT DISTINCT manager_id
    FROM quant1
    WHERE manager_id IS NOT NULL);

DEMO

Upvotes: 2

Related Questions