PostgreSQL incorrect sorting

后端 未结 2 1025
甜味超标
甜味超标 2020-12-09 18:25

I use PostgreSQL 9.3.3 and I have a table with one column named as title (character varying(50)).

When I have executed the following query:

select *         


        
2条回答
  •  情深已故
    2020-12-09 19:10

    It seems, that when sorting Oracle as well as Postgres just ignore non alpha numeric chars, e.g.

      select '*' 
       union all
      select '#' 
       union all
      select 'A'
       union all
      select '*E'
       union all
      select '*B'
       union all
      select '#C'
       union all
      select '#D'
    order by 1 asc
    

    returns (look: that DBMS doesn't pay any attention on prefix before 'A'..'E')

      *
      #
      A
      *B
      #C
      #D
      *E
    

    In your case, what Postgres actually sorts is

    '', 'A' and 'Example'

    If you put '#' in the middle od the string, the behaviour will be the same:

      select 'A#B'
       union all
      select 'AC'
       union all
      select 'A#D'  
       union all
      select 'AE' 
    order by 1 asc
    

    returns (# ignored, and so 'AB', 'AC', 'AD' and 'AE' actually compared)

      A#B
      AC
      A#D
      AE
    

    To change the comparison rules you should use collation, e.g.

      select '#' collate "POSIX"
       union all
      select 'A' collate "POSIX"
       union all
      select '#Example' collate "POSIX"
    order by 1 asc
    

    returns (as it required in your case)

      #
      #Example
      A
    

提交回复
热议问题