Search code examples
mysqlselectjoinleft-joininner-join

MYSQL: Formatting values of a column in the output


I have a table which looks as below:

id   name   value
123  name1  ,
345  name2  N/A
456  name3  ,value1

I want my output to be like

id   name   value
123  name1  undefined
345  name2  undefined
456  name3  value1

If it is just , or N/A then output should be undefined otherwise replace , from beginning of value

Select id, name 
    (case when value regexp ',' then 'undefined'
          when value regexp 'N/A' then 'undefined'
        end) 

However, it is replacing everything with value undefined


Solution

  • Assuming, we don't care about replacing comma(s) from value. Then, replace comma with empty string and then get the length

    LENGTH(REPLACE(value, ',', ''))=0
    

    If that is 0, then value had only ,.

    Select id, name, 
        (case when value = 'N/A' then 'undefined'
              when LENGTH(REPLACE(value, ',', ''))=0 then 'undefined'
              else REPLACE(value, ',', '')
            end) value from <table_name>