Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Match multiple columns with same value SQL

Tags:

sql

Suppose the table has columns like akey1 , bkey2 , ckey3 and many more like it.
Is there way to search for a common value

SELECT * FROM table WHERE %key% LIKE 'xyz'

other than using multiple AND , OR conditions . Doesn't matter if solution is DBMS specific .

like image 631
Mudassir Hasan Avatar asked Jan 02 '13 02:01

Mudassir Hasan


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 I match multiple values 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

Short of dynamic sql, you will have to spell out each of the column names. But you can get a bit of syntactic shortcut and only list the constant once:

SELECT * FROM table WHERE 'xyz' IN (akey1, bkey2, ckey3)

With dynamic sql, you still have to issue this same query... but you can at least use string tools to build it up first, and if you want to use wildcard matching you can look in the information_schema.columns view to find them. However, that involves opening and iterating over a cursor or returning the column data to the client, either of which involves more work than just listing out column names in the original query. Hopefully you know your database at least that well before you start issues queries to it.

like image 77
Joel Coehoorn Avatar answered Nov 03 '22 11:11

Joel Coehoorn