sqloracle-databasesortingsql-order-bynls-sort

How to sort all numbers before letters with linguistic sorting?


In an Oracle SQL query which uses binary sorting rules, numbers are sorted before letters. But if the query uses a language specific collation to enable linguistic sorting, then numbers are sorted after letters.
Example: https://dbfiddle.uk/xfXRj2sv
Extended example: https://dbfiddle.uk/vY2ovuam

This differs from e.g. .NET sorting, where even with linguistic sorting the numbers are sorted before letters.
Example with the expected order: https://dotnetfiddle.net/RulPpO
Extended example: https://dotnetfiddle.net/gytC9a

How can I use linguistic sorting and sort numbers before letters in an Oracle SQL query?

Note: This question is similar to How to sort numbers before letters with linguistic sorting?, but expanded to also include numbers in the middle of a string.


Solution

  • You can get a result that matches your .NET fiddle with GENERIC_M_AI or UCA_0620_DUCET_AI multilingual collation - even if you only have one language to handle:

    select val
    from t
    order by val COLLATE GENERIC_M_AI
    
    VAL
    1
    2
    aA1
    äB2
    aC3
    AD4
    X1A1
    XAA2
    select val
    from t
    order by val COLLATE UCA0620_DUCET_AI
    
    VAL
    1
    2
    aA1
    äB2
    aC3
    AD4
    X1A1
    XAA2

    fiddle