How can I sort by a table column in varying cases (Oracle)

前端 未结 5 1172

How can I sort a table with a column of varchar2 with characters in varying cases (UPPER and lower)?

For example, when I do an order by

5条回答
  •  梦如初夏
    2021-02-12 11:09

    Another option is the use of the NLSSORT function to perform linguistic sorting:

    SQL> with test as (select 'ANNIE' as col from dual
      2      union all select 'BOB' from dual
      3      union all select 'Daniel' from dual
      4      union all select 'annie' from dual
      5      union all select 'bob' from dual
      6      union all select 'Ångström' from dual
      7      union all select 'ångström' from dual)
      8  select col
      9  from test
     10  order by nlssort(col, 'NLS_SORT = WEST_EUROPEAN')
     11  /
    
    COL
    ----------
    Ångström
    ångström
    ANNIE
    annie
    BOB
    bob
    Daniel
    

    The advantages are more flexibility. One can sort characters with accents as well as different cases together. One can choose to treat some characters in a language specific way by specifying different values for NLS_SORT. Defines an order within the set of equivalent characters. So 'A' and 'a' are sorted together, but within the 'a's, the upper case comes first. Disadvantages I expect that NLSSORT uses more CPU than LOWER, though I have not bench marked it. And NLSSORT will only use a prefix of longer strings:

    The string returned, also known as the collation key, is of RAW data type. The length of the collation key resulting from a given char value for a given collation may exceed 2000 bytes, which is the maximum length of the RAW value returned by NLSSORT. In this case, NLSSORT calculates the collation key for a maximum prefix, or initial substring, of char so that the calculated result does not exceed 2000 bytes. For monolingual collations, for example FRENCH, the prefix length is typically 1000 characters. For multilingual collations, for example GENERIC_M, the prefix is typically 500 characters. The exact length may be lower or higher depending on the collation and the characters contained in char.

提交回复
热议问题