I have two tables.
Table one:
ID COLOR
1 white
2 red
3 black
4 blue
5 yellow
Table two:
ID COLOR
1 white
2 white
3 red
4 black
Output should be:
1 white
2 red
3 black
(exclude 2 values that don't exist in second table - blue and yellow + exclude second white).
I tried different JOIN and EXIST queries, no luck. Thanks.
How to Select All Records from One Table That Do Not Exist in Another Table in SQL? We can get the records in one table that doesn't exist in another table by using NOT IN or NOT EXISTS with the subqueries including the other table in the subqueries.
Using Joins Instead of IN or EXISTS An alternative for IN and EXISTS is an INNER JOIN, while a LEFT OUTER JOIN with a WHERE clause checking for NULL values can be used as an alternative for NOT IN and NOT EXISTS.
SQL Server EXISTS operator overview The EXISTS operator returns TRUE if the subquery returns one or more rows. In this syntax, the subquery is a SELECT statement only.
where exists
is appropriate for this.
select *
from t1
where exists
(select 1
from t2 where color = t1.color);
demo here
The subquery is a correlated subquery (as it refers to a value from the other query), and as such it is executed for every row of the outer query. So all the inner query needs to do, is check and see if the colour from the outer query (and first table) is present in the second table.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With