Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

T-SQL query: where column not in is giving wrong result

I have two table A and table B, the common column in both table is Name, I want to know what are name in Table A that is not in table B

when I do:

Select Name from A where Name not in (Select Name from B)

I am sure there are 2 name in Table A that is not in table B

but the result returns nothing

These name column in table A and B has the same datatype varchar(50)

so I copy the result of Name column and Insert into a new table and do the same query, and this time it returns the right result. what bug could this be?

example:

Table A
Name:
Kevin
Dexter
David 
John
Marry

Table B
Name:
Kevin
Dexter
David 

So the query should return 'John', 'Marry' but it doesn't return in my original table, but it returns in another table I create and insert.

Thanks!

like image 843
user3399111 Avatar asked May 18 '26 11:05

user3399111


2 Answers

You probably have a NULL name on B, this makes the NOT IN false for every row. You should use NOT EXISTS instead:

SELECT Name 
FROM A 
WHERE NOT EXISTS (SELECT 1 FROM B 
                  WHERE A.Name = B.Name)
like image 66
Lamak Avatar answered May 21 '26 04:05

Lamak


Obviously it is because of NULL value on some rows in table B. You can do what you want with EXCEPT

SELECT Name FROM TableA
EXCEPT
SELECT Name FROM TableB
like image 28
Giorgi Nakeuri Avatar answered May 21 '26 05:05

Giorgi Nakeuri



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!