1

How to write multiple column "in" sql query syntax?

Example :-

I am looking for the name : Peter in all of these 3 columns (or) any of these 3 columns : colA, colB, colC from the table : TableA

select * from TableA
where (colA, colB, colC) in 'Peter'

Table has the columns in a Pivot format. Alternate would be .. writing a union query for each column in syntax.

1
  • why not using OR... i.e. colA in 'Peter' OR colB in 'Peter' OR colC in 'Peter' ....? Commented Apr 9, 2019 at 3:45

3 Answers 3

9

Can you try

select * from TableA
where 'Peter' in (colA, colB, colC) 
Sign up to request clarification or add additional context in comments.

6 Comments

I am testing this result in real time.. I will accept in few mins
This is a valid syntax, at least in SQL Server. To the optimiser it is equivalent to 'Peter' = colA OR 'Peter' = colB OR 'Peter' = colC
@VladimirBaranov , Thanks .. I am with you in this syntax. It is valid
This is a valid syntax in SQL Server, MySql, Postgresql. I'm sure :)
@RyanNghiem ... sorry this syntax is breaking .. when we try to pass more than one name , it becomes as Sub Query for IN. This query will work only if we have one value to it
|
4

Depending on the cardinality of the dataset, values in those columns equal to "Peter", the effects could be similar or different for the following two scenarios:

select * from TableA
where colA = 'Peter' OR colB = 'Peter' OR colC = 'Peter'

and

select *
from TableA
where colA = 'Peter'

union

select *
from TableA
where colB = 'Peter'

union

select *
from TableA
where colC = 'Peter'

However, my recommendation would be to use the UNION version since it might give better performance in scenarios where the cardinality of "Peter" in each column is small.

4 Comments

My existing query has union on it . i am working on replacing the lengthy syntax
@goofyui In my opinion you're trying to solve a nonproblem. However, I'm glad you found your answer and in the meantime I've found out something new. +1 for Ryan
@Radhu, I am with you. +1 for Ryan :)
Ryan's syntax is breaking when we pass more than one name. In the real time scenario, this will become as a Subquery for IN. I will have to use OR syntax.
2

In your case, this is ideal since you are looking for a single name

select * from TableA
where colA='Peter' OR colB='Peter'OR colC='Peter'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.