Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL - IN vs. NOT IN

Tags:

sql

Suppose I have a table with column which takes values from 1 to 10. I need to select columns with all values except for 9 and 10. Will there be a difference (performance-wise) when I use this query:

SELECT * FROM tbl WHERE col NOT IN (9, 10)

and this one?

SELECT * FROM tbl WHERE col IN (1, 2, 3, 4, 5, 6, 7, 8)
like image 462
kyooryu Avatar asked Jun 03 '13 07:06

kyooryu


People also ask

What is in and not in in SQL?

IN, NOT IN operators in SQL are used with SELECT, UPDATE and DELETE statements/queries to select, update and delete only particular records in a table those meet the condition given in WHERE clause and conditions given in IN, NOT IN operators. I.e. it filters records from a table as per the condition.

Which is faster in SQL in or not in?

If you can write your query either way, IN is preferred as far as I'm concerned. Show activity on this post. Same for the other one, with 8 times = instead. So yes, the first one will be faster, less comparisons to be done.

Which is better not in or <> in SQL?

NOT EXISTS tends to perform better in SQL Server than LOJ and avoids the issues with NULLs so I prefer it.

What is the difference between in and not in operator?

The EXCEPT operator removes duplicate rows from the results and returns only DISTINCT records. On the other hand, the NOT IN operator will return duplicate records. Let's take a look at this with the help of an example.


2 Answers

Use "IN" as it will most likely make the DBMS use an index on the corresponding column.

"NOT IN" could in theory also be translated into an index usage, but in a more complicated way which DBMS might not "spend overhead time" using.

like image 184
Serge Avatar answered Oct 20 '22 01:10

Serge


When it comes to performance you should always profile your code (i.e. run your queries few thousand times and measure each loops performance using some kind of stopwatch. Sample).

But here I highly recommend using the first query for better future maintaining. The logic is that you need all records but 9 and 10. If you add value 11 to your table and use second query, logic of your application will be broken that will lead to bug, of course.

Edit: I remember this was tagged as php that's why I provided sample in php, but I might be mistaken. I guess it won't be hard to rewrite that sample in the language you're using.

like image 21
Leri Avatar answered Oct 20 '22 01:10

Leri