MrB
MrB

Reputation: 1594

Mysql where column=id vs where column in (ids)

I was wondering why do we use

where column=id

vs

where column in (id)

I know that the first will only allow a single id while the second will allow multiple ids, However why don't we always use in even for a single column search?

In other words why do we not always use "where column in (id)"?

Upvotes: 1

Views: 102

Answers (1)

Ross Smith II
Ross Smith II

Reputation: 12189

The two are essentially the same, so they are interchangeable. It is a personal preference which one to use.

Personally, I would use = when I know I will never check for more than one value. I would use IN if there's a good chance I will modify the query later to add new values to the list.

When performance isn't a concern, instead of IN, I sometimes use REGEXP as it more succinct, and requires less typing:

WHERE column REGEXP '^(value1|value2)$'

or

WHERE column REGEXP '[[:<:]](value1|value2)[[:>:]]'

Of course the less well known 'null-safe' equality operator <=>:

WHERE column <=> id

does not have an equivalent IN version.

Upvotes: 3

Related Questions