Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL query city names starting And ending with vowels

Tags:

I wrote this code (db2) and it works just fine, but I'm wondering, is there a shorter way to write this?

Select Distinct city
From   station
Where  city Like 'A%a'
       Or city Like 'A%e'
       Or city Like 'A%i'
       Or city Like 'A%o'
       Or city Like 'A%u'
       Or city Like 'E%a'
       Or city Like 'E%e'
       Or city Like 'E%i'
       Or city Like 'E%o'
       Or city Like 'E%u'
       Or city Like 'I%a'
       Or city Like 'I%e'
       Or city Like 'I%i'
       Or city Like 'I%o'
       Or city Like 'I%u'
       Or city Like 'O%a'
       Or city Like 'O%e'
       Or city Like 'O%i'
       Or city Like 'O%o'
       Or city Like 'O%u'
       Or city Like 'U%a'
       Or city Like 'U%e'
       Or city Like 'U%i'
       Or city Like 'U%o'
       Or city Like 'U%u';
like image 565
cristo spreeuwers Avatar asked Jul 06 '17 18:07

cristo spreeuwers


2 Answers

I am not a DB2 expert but this should be fairly portable:

WHERE LEFT(city,1) IN ('A', 'E', 'I', 'O', 'U')
  AND RIGHT(city,1) IN ('a', 'e', 'i', 'o', 'u')

You may want to normalize it all to upper case to avoid problems with cities that for some reason start with a lower case letter or end with an upper case letter.

WHERE UPPER(LEFT(city,1)) IN ('A', 'E', 'I', 'O', 'U')
  AND LOWER(RIGHT(city,1)) IN ('a', 'e', 'i', 'o', 'u')
like image 134
fhossfel Avatar answered Oct 11 '22 14:10

fhossfel


You can use REGEXP in MySQL to operate Regular Expression

SELECT DISTINCT city 
FROM station 
WHERE city REGEXP '^[aeiou].*[aeiou]$';

For people who don't familiar with Regular Expression

^[aeiou]    // Start with a vowel
.*          // Any characters at any times
[aeiou]$    // End with a vowel
like image 32
kestory Avatar answered Oct 11 '22 13:10

kestory