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

前端 未结 5 1182

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:26

    If you're on relatively recent versions of Oracle, you should look at setting NLS_SORT/NLS_COMP, rather than using the LOWER() function.

    If you don't want to globally affect the instance, you can use the NLSSORT() function to set the NLS_SORT for the scope of a specific query.

    SQL> create table case_insensitive(a varchar2(10));
    
    Table created.
    
    SQL> insert into case_insensitive values('D');
    
    1 row created.
    
    SQL> 
    SQL> 
    SQL> c/'D/'c
      1* insert into case_insensitive values('c')
    SQL> /
    
    1 row created.
    
    SQL> c/'c/'B
      1* insert into case_insensitive values('B')
    SQL> /
    
    1 row created.
    
    SQL> c/'B/'a
      1* insert into case_insensitive values('a')
    SQL> /
    
    1 row created.
    
    SQL> commit;
    
    Commit complete.
    
    SQL> select * from case_insensitive;
    
    A
    ----------
    D
    c
    B
    a
    
    SQL> select * from case_insensitive order by a;
    
    A
    ----------
    B
    D
    a
    c
    
    SQL> select * from case_insensitive order by nlssort(a,'NLS_SORT=BINARY_CI'); 
    
    A
    ----------
    a
    B
    c
    D
    

    A good example of this can be found here.

提交回复
热议问题