Reputation: 32241
I got two tables in my DB, users and gifts. The user table got id and data, the gifts table got gift_id, user_id and data.
gitst.user_id associated with users.id
How can I get all the user_id from gifts table that not appear in users table?
Upvotes: 0
Views: 182
Reputation: 49260
One way to do it is using the except
operator.
select user_id from gifts
except
select id from users
Except
gives you the difference of two sets.
Let's say set A = {1,2,3} B={3,4,5,6}.
A-B = {1,2} because 3
exists in both the sets and 1,2 exist in A but not in B
B-A = {4,5,6} 3 is common to both sets and 4,5,6 exist in B but not in A
You can also do
select user_id from gifts
where user_id not in (select id from users)
or
select user_id from gifts g
where not exists (select 1 from users where id = g.user_id)
Upvotes: 1