Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mysql CASE with multiple substring legths

Tags:

sql

mysql

I have hundreds of phone number of the world. Each has its country prefix (the prefix varies: some are 1, 2, 3 or 4 digit long) + the phone number. I want to write a mysql query, which will show me the Country name by using the prefix.

Example : If i use sub-string for the first 3 digits, its working fine. But how i can show the prefixes which are 2 or 4 digit long ?

SELECT(
CASE (SUBSTR(Number,1,3))
WHEN '998' Then 'Uzbekistan '
WHEN '996' Then 'Kyrgyzstan '
WHEN '995' Then 'Georgia '
.....
....
ELSE 'OTHERS' END ) AS Country
like image 353
Ayaz Avatar asked Jan 20 '26 06:01

Ayaz


1 Answers

A simple solution is based on the fact that the CASE statement is evaluated sequentially.

SELECT(
    CASE 
      WHEN SUBSTR(Number,1,2) = '23' Then 'Try For 23 '   
      WHEN SUBSTR(Number,1,3) = '998' Then 'Uzbekistan '
      WHEN SUBSTR(Number,1,3) = '996' Then 'Kyrgyzstan '
      WHEN SUBSTR(Number,1,3) = '995' Then 'Georgia '
     .....
     ....
     ELSE 'OTHERS' END ) AS Country
like image 113
ScaisEdge Avatar answered Jan 21 '26 19:01

ScaisEdge



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!