Reputation: 563
I have two tables in my database:
table_A: table_B:
id user id user
1 Mike 1 Mike
2 Dan 2 Dan
3 Tom 3 Tom
4 Lina 4 Lina
5 Cynthia
6 Sam
My aim is to identify which users in Table_B do not exist in Table_A based on id. I'm new in SQL, and this is what i came up with:
SELECT id FROM Table_B
WHERE B.id NOT IN ( SELECT A.id from Table_A)
Most likely my logic is wrong, so i'd appreciate any guidance please.
Upvotes: 3
Views: 302
Reputation: 575
You are close. It seems to me that the only thing you need to change is the A.ID and B.ID reference
SELECT id FROM Table_B B
WHERE B.id NOT IN ( SELECT A.id from Table_A A)
Since you are referring to Table_A as A and table_B as B you need to create the alias name.
You could also use
SELECT id FROM Table_B B
WHERE NOT EXISTS ( SELECT A.id from Table_A A where A.ID = B.ID)
but i would prefer the first one.
Upvotes: 0
Reputation: 2506
You can use sub-query in WHERE
clause predicate NOT IN
Then it will return the id
present in table_B
only
Sub-Query
This query return id
from table_A
SELECT table_A.id FROM table_A
Then it will be passed to NOT IN
clause which will return boolean true
on every record set iteration if not matched. So id
5 and 6 only return in the main query.
Final Query
SELECT table_B.id, table_B.name FROM table_B WHERE table_B.id NOT IN (SELECT table_A.id FROM table_A);
OR
to select all column use symbol *
instead of column lists
SELECT * FROM table_B WHERE table_B.id NOT IN (SELECT table_A.id FROM table_A);
Upvotes: 1
Reputation: 4844
You can use EXISTS function.
Select * from table_B where Not EXISTS (select * from table_A)
Upvotes: 0