SQL Between clause with strings columns

后端 未结 6 2068
暖寄归人
暖寄归人 2020-11-27 19:24

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

相关标签:
6条回答
  • 2020-11-27 20:04

    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

    0 讨论(0)
  • 2020-11-27 20:11

    Another query that would get countries that start with b as well as A, would be:

    Select * from country where name between 'a' and 'c'
    
    0 讨论(0)
  • 2020-11-27 20:13
    Select * from country where substring(name FROM 1 FOR 1) between 'A' and 'B';
    
    0 讨论(0)
  • 2020-11-27 20:19

    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'
    
    0 讨论(0)
  • The reason this statement didn't work is SQL pads the string with whitespace until it's the same length as the comparing string. So, in comparison, sql compared b followed by several blanks with b******. Because whitespace appears before all the other letters, sql decided b***** came after b[6 spaces]. So it shouldn't be displayed.

    0 讨论(0)
  • 2020-11-27 20:25

    The result's accurate, but you may be misunderstanding. x between a and b means x>=a and x<=b. (See the PostGRES documentation for details.)

    If you want to get lines that start with either an a or a b, say what you mean:

    select * from country where name like 'a%' or name like 'b%'
    

    like uses the table indices so you'll get full performance for using this.

    0 讨论(0)
提交回复
热议问题