Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select a Range of Letters

Tags:

sql

sql-server

How to select row with name starting with 'A' until name starting with 'D'? And sort them alphabetically? Something like a combination of LIKE and =<> ?

Sample Table:

ID       Name
4001     Spartakol
4002     Tabunjong
4003     Mabini
4004     Carlos
4005     Antonio
4006     Babsy
4007     Jose
4008     David
4009     Cruz

Sample Output:

4005     Antonio
4006     Babsy
4004     Carlos
4009     Cruz
4008     David

with name starting with 'Cr' until name starting with 'D'

Sample Output:

4009     Cruz
4008     David
like image 834
Square Ponge Avatar asked Jul 07 '13 15:07

Square Ponge


4 Answers

Here's another simpler solution

SELECT * FROM table_name WHERE name BETWEEN "A" AND "E" ORDER BY name
like image 182
Chigozie Orunta Avatar answered Sep 23 '22 22:09

Chigozie Orunta


Guffa's answer is probably the most efficient. To be complete, you could also use

LIKE '[a-d]%'

Depending on your database COLLATION, LIKE might be case sensitive or not.

like image 20
iDevlop Avatar answered Sep 19 '22 22:09

iDevlop


Select the names from 'A' up to, but not including 'E':

select ID, Name
from SampleTable
where Name >= 'A' and Name < 'E'
order by Name

As this is a plain comparison, it can use an index if you have one for that field.

like image 20
Guffa Avatar answered Sep 22 '22 22:09

Guffa


select id, name from Your Table where LOWER(LEFT(name, 1)) between 'a' and 'd'; order by name;

like image 21
doglin Avatar answered Sep 22 '22 22:09

doglin