Select NOT IN multiple columns

SqlDatabaseMultiple Columns

Sql Problem Overview


I need to implement the following query:

SELECT * 
FROM   friend 
WHERE  ( friend.id1, friend.id2 ) 
         NOT IN (SELECT id1, 
                        id2 
                 FROM   likes) 

But NOT IN can't be implemented on multiple columns. How do I write this query?

Sql Solutions


Solution 1 - Sql

I'm not sure whether you think about:

select * from friend f
where not exists (
	select 1 from likes l where f.id1 = l.id and f.id2 = l.id2
)

it works only if id1 is related with id1 and id2 with id2 not both.

Solution 2 - Sql

Another mysteriously unknown RDBMS. Your Syntax is perfectly fine in PostgreSQL. Other query styles may perform faster (especially the NOT EXISTS variant or a LEFT JOIN), but your query is perfectly legit.

Be aware of pitfalls with NOT IN, though, when involving any NULL values:

Variant with LEFT JOIN:

SELECT *
FROM   friend f
LEFT   JOIN likes l USING (id1, id2)
WHERE  l.id1 IS NULL;

See @Michał's answer for the NOT EXISTS variant.
A more detailed assessment of four basic variants:

Solution 3 - Sql

I use a way that may look stupid but it works for me. I simply concat the columns I want to compare and use NOT IN:

SELECT *
FROM table1 t1
WHERE CONCAT(t1.first_name,t1.last_name) NOT IN (SELECT CONCAT(t2.first_name,t2.last_name) FROM table2 t2)

Solution 4 - Sql

You should probably use NOT EXISTS for multiple columns.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGunjan NigamView Question on Stackoverflow
Solution 1 - SqlMichał PowagaView Answer on Stackoverflow
Solution 2 - SqlErwin BrandstetterView Answer on Stackoverflow
Solution 3 - SqlvacolaneView Answer on Stackoverflow
Solution 4 - SqlRaoul GeorgeView Answer on Stackoverflow