1

I have two conditions that are causing the CASE statement not to work as intended. I've tried changing which condition comes first, but it still only proceeds with one of them. Any suggestions?

CASE statement that returns only the value before the first '(' and replaces all instances of 'Metallic' with 'M':

CASE
WHEN `order_option`.`value` LIKE '%(%)%' THEN SUBSTRING_INDEX(`order_option`.`value`,' (', 1)
WHEN `order_option`.`value` LIKE '%Metallic%' THEN REPLACE (`order_option`.`value`,'Metallic','M')
ELSE `order_option`.`value`
END AS `Option`,

Current data

`value`
--------
Red Metallic (999)
Blue (745)

Expected results

`Option`
--------
Red M
Blue

Thank you in advance!

3
  • Your code mentions value; your data mentions Option. The LIKE looks for just (, but the SUBSTRING_INDEX looks for ` (`.
    – Rick James
    Commented Apr 14, 2020 at 0:39
  • ‘Value’ is the column name for the product option from the ‘order_option’ table
    – msklut
    Commented Apr 14, 2020 at 0:41
  • See if my edit is "correct".
    – Rick James
    Commented Apr 14, 2020 at 0:59

1 Answer 1

1

You have no chance, besides change the metallooc text first and also do a substing on it

Schema (MySQL v8.0)

CREATE TABLE Option1 (
  `Text1` VARCHAR(18),
  `num` INTEGER
);

INSERT INTO Option1
  (`Text1`, `num`)
VALUES
  ('Red Metallic (999)', '0'),
  ('Blue (745)', '0');

Query #1

SELECT
CASE
WHEN `text1` LIKE '%Metallic%' THEN SUBSTRING_INDEX(REPLACE (`text1`,'Metallic','M'),' (', 1)
WHEN `text1` LIKE '%(%)%' THEN SUBSTRING_INDEX(`text1`,' (', 1)

ELSE `text1`
END AS `Option1`
FROM Option1;

| Option1 |
| ------- |
| Red M   |
| Blue    |

View on DB Fiddle

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.