Checking multiple columns for one value

MysqlSqlSelectQuery Optimization

Mysql Problem Overview


I have a table that has columns like this for example:

id,col1,col2,col3,col4

Now, I want to check if ANY of col1, col2, col3, col4 have the passed in value.

The long way to do it would be..

SELECT * FROM table WHERE (col1 = 123 OR col2 = 123 OR col3 = 123 OR col4 = 123);

I guess it's the opposite version of IN.

Is there an easier way to do what I want?

Mysql Solutions


Solution 1 - Mysql

You can use the IN predicate, like so:

SELECT * FROM table WHERE 123 IN(col1, col2, col3, col4);

SQL Fiddle Demo


> it's the opposite version of IN.

No it is not, It is the same as using the ORs the way you did in your question.


To clarify this:

The predicate IN or set membership is defined as1:

enter image description here

Where the Value Expression can be either 2:

enter image description here

So it is fine to do it this way, using the value expression 123, which is a literal.


1, 2: Images from: SQL Queries for Mere Mortals(R): A Hands-On Guide to Data Manipulation in SQL

Solution 2 - Mysql

I had a similar problem and solved it this way: SELECT * FROM table WHERE col1 OR col2 IN(SELECT xid FROM tablex WHERE somecol = 3)

Not sure if it is "the best way" but it works for me.

Thoughts?

Solution 3 - Mysql

You could do something like: (Note: Assuming the columns are numeric values. And, just incase the concatenated value creates the character sequence you are looking for, use a delimiter to distinguish the column values. Pipe (|) is the delimiter in this example.)

SELECT [ID]
    ,[Col1]
    ,[Col2]
    ,[Col3]
    ,[Col4]
FROM [Table1]
WHERE '123' IN (
    CAST([Col1] AS VARCHAR) + '|'
    + CAST([Col2] AS VARCHAR) + '|'
    + CAST([Col3] AS VARCHAR) + '|'
    + CAST([Col4] AS VARCHAR) + '|'
)

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
QuestionBrettView Question on Stackoverflow
Solution 1 - MysqlMahmoud GamalView Answer on Stackoverflow
Solution 2 - MysqlMilk ManView Answer on Stackoverflow
Solution 3 - MysqlDionicio GonzalezView Answer on Stackoverflow