Skip to content
Advertisement

Sort alphanumeric ID number

I have a database that every transactions get a alphanumeric ID. By when I write my query and use Order by it give me a wrong sequence.

For example:

As you can see the query is ordering A to Z then 0 to 9, but it should order 0 to 9 then A to Z

There is a way set a string to order it correctly?

Advertisement

Answer

It is very likely that Trincot’s observation (second comment under your question) is correct: You see ascending ordering with letters before digits (instead of the opposite), because your collation requires it.

From your profile I assume you are in Brazil, and your NLS_LANGUAGE parameter is 'BRAZILIAN PORTUGUESE', with the default NLS_SORT parameter (derived from NLS_LANGUAGE) of 'WEST_EUROPEAN'. It’s not Oracle’s choice; Brazilian Portuguese collation (or, rather more accurately, West-European collation) has digits after letters, not before them. See a demo at the end of this answer.

So, this explains the problem. How can you fix it?

If you have a lot of similar queries, and you must show digits before letters in all of them (or if you have ORDER BY in many places in a query – for example in analytic functions, or in match_recognize, etc.), then it makes sense to change the NLS_SORT parameter for the session, with

If you only need to do it in a single query, in the ORDER BY clause, you can just change the sort order locally (for that ORDER BY clause only, without affecting anything else) by using the NLSSORT function. Like this:

Here is a brief demo.

First, on my system, NLS_LANGUAGE is 'AMERICAN', with the default NLS_SORT (for this language) of 'BINARY'. This is why letters come after digits:

Now let me change my NLS_LANGUAGE to 'BRAZILIAN PORTUGUESE'. Then let’s see how this affected NLS_SORT (automatically), and what that does to the query:

Now, without changing the language, let me just change the collating sequence (NLS_SORT parameter) to 'BINARY' – and see how the query produces the desired result. We didn’t change the language, but we changed the collating sequence for the entire session. This will work for all other queries in the current session.

Finally, let me change NLS_SORT back to 'WEST_EUROPEAN' and use the NLSSORT function in the ORDER BY clause of the query to get the same result (the one you need) without touching the session parameters.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement