Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL Case in Select Statement with LIKE operator

Tags:

mysql

case

Is it possible to combine the CASE statement and the LIKE operator in a MySQL SELECT statement?

For Example, I am trying to query a database that stores data in a single column in either one of two formats (this is awful and hurts my head, but I cant change the data so it is what it is.). So sometimes the column numbers would have data like "6901xxxxxxxx" and sometimes it would have data like "91xxxxxxxxxxx".

What I would like to do is query the data like so -

SELECT     CASE digits       WHEN LIKE "6901%" THEN substr(digits,4)       WHEN LIKE "91%" THEN substr(digits,2)     END as "digits", FROM raw 

This obviously doesn't work but Im hoping its possible.

like image 200
HurnsMobile Avatar asked Aug 26 '10 21:08

HurnsMobile


People also ask

Does Like operator ignore case?

LIKE performs case-insensitive substring matches if the collation for the expression and pattern is case-insensitive. For case-sensitive matches, declare either argument to use a binary collation using COLLATE , or coerce either of them to a BINARY string using CAST .

How do you make a case-insensitive like a query in MySQL?

When searching for partial strings in MySQL with LIKE you will match case-insensitive by default*. If you want to match case-sensitive, you can cast the value as binary and then do a byte-by-byte comparision vs. a character-by-character comparision. The only thing you need to add to your query is BINARY .

Is like in MySQL case-sensitive?

By default, it's case-insensitive, and like with MySQL, you can change this behavior by modifying the collation setting.

How do I add a case to a MySQL query?

Definition and Usage. The CASE statement goes through conditions and return a value when the first condition is met (like an IF-THEN-ELSE statement). So, once a condition is true, it will stop reading and return the result. If no conditions are true, it will return the value in the ELSE clause.


2 Answers

Using the second form of CASE should work:

SELECT   CASE     WHEN digits LIKE '6901%' THEN substr(digits,4)     WHEN digits LIKE '91%' THEN substr(digits,2)   END as digits FROM raw 

Furthermore, you have a stray comma at the end of your SELECT.

like image 50
Daniel Vandersluis Avatar answered Sep 20 '22 13:09

Daniel Vandersluis


Try

SELECT     CASE true       WHEN digits LIKE "6901%" THEN substr(digits,4)       WHEN digits LIKE "91%" THEN substr(digits,2)     END as "digits", FROM raw 
like image 29
Tim Avatar answered Sep 18 '22 13:09

Tim