Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

SUBSTR CASE MySQL

I have the following table:

Fruits & Vegetables
3 Apples
2 Oranges
Cucumber

I need to extract a the first letter of the string using a substring and a case in mysql:
i.e. I need to extract 3, 2 & C

  • where if 3 then "Fruit"
  • where if 2 then "Fruit"
  • where if C then "Vegetable"

So I have used the following:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Type varchar(80)
AS
(case
    when SUBSTR('Fruits & Vegetables',1) = '3' then "Fruit"
when SUBSTR('Fruits & Vegetables',1) = '2' then "Fruit"
when SUBSTR('Fruits & Vegetables',1) = 'C' then "Vegetable"
else NULL
end),

what I get is Null as a result can someone tell me what is wrong with the code?

>Solution :

try this query

SUBSTR(fruits_and_vegetables, 1, 1)

SELECT 
(case when SUBSTR(fruits_and_vegetables, 1, 1) = '3' then "Fruit" 
when SUBSTR(fruits_and_vegetables,1,1) = '2' then "Fruit" 
when SUBSTR(fruits_and_vegetables,1,1) = 'C' then "Vegetable" 
else NULL END) as `Fruits & Vegetables` FROM `table_name`
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading