How to sort by numbers first with Oracle SQL query?

前端 未结 2 1679
一向
一向 2020-12-16 17:41

I have this table with a \'title\' field which is varchar2 and I want to select all rows and sort them first by number and then by the alphabet as it normally happens.

2条回答
  •  别那么骄傲
    2020-12-16 18:03

    the difference in behaviour that you're seeing is probably because of different NLS_SORT parameter setting. Consider:

    SQL> select * from nls_session_parameters where parameter='NLS_SORT';
    
    PARAMETER                      VALUE
    ------------------------------ ----------------------------------------
    NLS_SORT                       BINARY
    
    SQL> SELECT * FROM my_data order by title;
    
    TITLE
    -----
    321
    Abc
    Def
    
    SQL> alter session set nls_sort=french;
    
    Session altered
    
    SQL> SELECT * FROM my_data order by title;
    
    TITLE
    -----
    Abc
    Def
    321
    

    You can build a query that should give you the expected result regardless of your NLS_SORT session parameter setting, for example:

    SQL> SELECT *
      2    FROM my_data
      3   ORDER BY CASE
      4               WHEN regexp_like(title, '[0-9]+\.?[0-9]*') THEN
      5                1
      6               ELSE
      7                2
      8            END, title;
    
    TITLE
    -----
    321
    Abc
    Def
    

提交回复
热议问题