How to sort by numbers first with Oracle SQL query? How to sort by numbers first with Oracle SQL query? oracle oracle

How to sort by numbers first with Oracle SQL query?


Not an Oracle expert, but you are supposed to be able to do it without altering the session with

SELECT * FROM my_data SORT by NLSSORT(title,’NLS_SORT=BINARY_AI’)

where you can change the NLS_SORT= to fit your needs (here are the list of values)

Keep in mind that docs says that this will force table scan, so it might be beneficial to filter them first (but if you are selecting all the table scan is what you are going to use anyway).

The reason why SQL Developer exhibits different behaviour is probably because it changes the session.


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                       BINARYSQL> SELECT * FROM my_data order by title;TITLE-----321AbcDefSQL> alter session set nls_sort=french;Session alteredSQL> SELECT * FROM my_data order by title;TITLE-----AbcDef321

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-----321AbcDef