0

I have data in multiple columns

col_a        | col_b            | col_c
-----------------------------------------------
good car     | medium sandwitch | good computer
bad computer | good wall        | bad wall

and I want to select the first value that starts with "good" from these three columns

result
---------
good car
good wall
4
  • And if there's no 'good' in any of the columns? Commented May 26, 2022 at 20:51
  • @jarlh then I don't want that row, but a default value or NULL would also be good. Commented May 26, 2022 at 20:51
  • Use a case expression. Commented May 26, 2022 at 20:52
  • might can use regex if in mysql Commented May 26, 2022 at 20:53

1 Answer 1

2

You can do this with a simple case expression:

select case
    when col_a like 'good%' then col_a
    when col_b like 'good%' then col_b
    when col_c like 'good%' then col_c
end result
from table

This will evaluate in order, so order the columns in the case statement in whatever order you wish to check.

--EDIT--

To remove the rows with no results, we have a few options:

Move this into a subquery (or CTE) with a where clause

select *
from
(
    select case
        when col_a like 'good%' then col_a
        when col_b like 'good%' then col_b
        when col_c like 'good%' then col_c
    end result
    from table
) a
where a.result is not null

Check all of them in your where clause

select case
    when col_a like 'good%' then col_a
    when col_b like 'good%' then col_b
    when col_c like 'good%' then col_c
end result
from table
where col_a like 'good%'
    or col_b like 'good%'
    or col_c like 'good%'
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, I tried this but my issue was I had a string, like this: then 'col_a'

Your Answer

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