Display blank if there are only two words in the column and only the third word is displayed

So, I'm trying to get an if statement working with a statement substring_index

that matches the requirements I'm looking for. I have a column called "product_name" that lists the names of all of my products, and the goal is to look at each row, determine if there are less than three words in the row. If there is, display the line as blank, if there is a third word, show only the third word (and if there are more than three words, display only the third word, hiding everything else).

I hope this makes sense.

So far I have a substring index that can find the first and second word based on the check ' '

in the string, however I am not sure how to form an if statement to parse the string and display empty if there are only two words.

I haven't done that yet to highlight the third word. Below is the code. Any help would be greatly appreciated.

SELECT substring_index(product_name, ' ', 1) AS a,
       substring_index(product_name, ' ', 2) AS b 
FROM products

      

+3


source to share


1 answer


You can do this with case

and the substring index - if the words are separated by exactly one space:



select (case when product_name not like '% % %' then ''
             else substring_index(substring_index(product_name, ' ', 3), ' ', -1)
        end)

      

+1


source







All Articles