Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking multiple columns for one value

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?

like image 382
Brett Avatar asked Dec 17 '12 14:12

Brett


People also ask

How do I check if multiple columns have the same value in SQL?

In SQL, problems require us to compare two columns for equality to achieve certain desired results. This can be achieved through the use of the =(equal to) operator between 2 columns names to be compared.

How do you check if a value is in multiple columns?

You can use the MATCH() function to check if the values in column A also exist in column B. MATCH() returns the position of a cell in a row or column. The syntax for MATCH() is =MATCH(lookup_value, lookup_array, [match_type]) . Using MATCH, you can look up a value both horizontally and vertically.

How do I Lookup multiple values in one column in SQL?

Note – Use of IN for matching multiple values i.e. TOYOTA and HONDA in the same column i.e. COMPANY. Syntax: SELECT * FROM TABLE_NAME WHERE COLUMN_NAME IN (MATCHING_VALUE1,MATCHING_VALUE2);

How do I check if three columns have the same value in mysql?

The long way to do it would be.. SELECT * FROM table WHERE (col1 = 123 OR col2 = 123 OR col3 = 123 OR col4 = 123);


1 Answers

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

like image 88
Mahmoud Gamal Avatar answered Sep 28 '22 12:09

Mahmoud Gamal