Nikita Gupta Nikita Gupta - 1 month ago 8
MySQL Question

mysql query to Identify which sql table column contains given string

Given:

TABLE : columns(column1(primary key),column2,column3)

column1 column2 column3
1920 abc def
1930 xyz hji
1940 def abc


Now, how to find column_name among column2 or column3 if we are given with a string in those columns?

For eg:we will be always given column 1 value i.e 1920; Some string from column 2 or column3 will be given too for eg: abc. So, we need to identify in 1920 "abc" was in column1 or column2 via mysql query.

Answer

You can use CASE

SELECT CASE WHEN column2 = 'abc' THEN 'column2'
            WHEN column3 = 'abc' THEN 'column3'
       END AS which_column
FROM yourTable
WHERE column1 = 1920

DEMO

Comments