Search code examples
sqlpostgresqlwhere-clausewhere-in

Postgresql: is it possible to tell in which column the search string was found?


how to tell in which column the search string was found?

My query

 select DISTINCT t1.id,
 t2.position ,
 t3.name ,
 t4 age

 FROM table1 AS t1 
  LEFT JOIN  table2 AS t2 on t1.id = t2.fk_id 
  LEFT JOIN  table3 AS t3  on t3.fk_id = t2.fk_id 
 LEFT JOIN  table4 AS t4  on t4.fk_id = t3.fk_id 
 WHERE 
  t2.position like ANY(['Real Estate Agent ','25']) 
  OR          
  t3.name like ANY(['Real Estate Agent ','25'])
  OR
  t4 age like ANY(['Real Estate Agent ','25'])

Solution

  • You would copy the conditions in the select:

    select . . .,
           ((case when t2.position like ANY(['Real Estate Agent ','25']) then 'position;' else '' end) ||
            (case when t2.name like ANY(['Real Estate Agent ','25']) then 'name;' else '' end) ||
            (case when t2.age like ANY(['Real Estate Agent ','25']) then 'age;' else '' end) 
           ) as matching_columns
    . . .