Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Between clause with strings columns

Tags:

I want to make a search using "between" clause over a string column. Doing some test I got this:

Let's assume that there is a country table with a "name" column of type varchar. If I execute this query:

Select * from country where name between 'a' and 'b'

I got this result:

Argentina
.
.
.
Argelia.

It excludes those countries that starts with B which I found a little bit weird.

Is there a way to do this search in a more accurate way? Any other ideas for make this search?

Thanks in advance

like image 395
Cheluis Avatar asked May 12 '11 15:05

Cheluis


2 Answers

The expression

name between 'A' and 'B'

is equivalent to

name>='A' and name<='B'

So 'Argentina' is >='A' and <='B' and it satisfies the condition. But 'Bolivia' is NOT <='B'. 'Bolivia'>'B'. It doesn't just look at the first letter: it looks at the whole string. Which is surely the way it ought to be: if it didn't do this, there'd be no way to say that you wanted a range that included 'Smith' but not 'Smithers'.

To accomplish what you want, you could say:

substr(name,1,1) between 'A' and 'B'

or:

name like 'A%' or name like 'B%'

or:

name>='A' and name<'C'
like image 147
Jay Avatar answered Sep 21 '22 15:09

Jay


i think i know how to solve your problem. u can try adding extra character in the back like this

select * from tablea where column1 between 'ABC' and 'ACD'+'Z'

this will return a result from ABC% to ACE

like image 25
Ariwibawa Avatar answered Sep 20 '22 15:09

Ariwibawa