Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WHERE x IN (5) vs WHERE x = 5 ... why use IN?

Tags:

syntax

sql

mysql

Something I've noticed recently is people using IN where it seems kind of inappropriate. I'm feeling like I'm missing a trick - perhaps there are speed gains or something?

This query:

SELECT * FROM pages WHERE is_visible IN ($visibility)

Why use that? Why not:

SELECT * FROM pages WHERE is_visible = $visibility

Sure, if it were this:

SELECT * FROM pages WHERE is_visible 
IN ($visibility,$invisibility,$somethingelse)

Then WHERE x IN (1,2,3) is a better alternative to WHERE x = 1 OR x = 2 OR x = 3, right? But surely this is the only scenario where you should use IN?

Anyway thanks for your time - I look forward to your replies!

like image 410
ledneb Avatar asked May 15 '09 15:05

ledneb


People also ask

What is the difference between the X 5 and X 5?

Answer: BRO NOTHING THEY ARE SAME .

What is the difference between a 5 and a == 5 in C++?

So it's cleared now, ,both are not same, = is an Assignment Operator it is used to assign the value of variable or expression, while ==is an Equal to Operator and it is a relation operator used for comparison (to compare value of both left and right side operands).


3 Answers

Maybe it is unknown wether $visibility refers to a single value or multiple values? Doesn't quite fit your example, but I have seen such use in other places.

like image 158
Thomas Lötzer Avatar answered Oct 19 '22 23:10

Thomas Lötzer


Then WHERE x IN (1,2,3) is a better alternative to WHERE x = 1 OR x = 2 OR x = 3, right? But surely this is the only scenario where you should use IN?

No, you can use IN with a subquery as well.

... where field in (select field from another_table)

like image 32
Otávio Décio Avatar answered Oct 19 '22 23:10

Otávio Décio


Maybe $visibility is dynamically generated, like this:

$visibility = implode(', ', array_map('intval', array(1, 2, 3)));

Where array(1, 2, 3) may come from untrusted sources.

like image 33
Ionuț G. Stan Avatar answered Oct 20 '22 00:10

Ionuț G. Stan