Thiago Moraes
Thiago Moraes

Reputation: 617

Sorting results on Oracle as ASCII

I'm doing a query that returns a VARCHAR2 and some other fields. I'm ordering my results by this VARCHAR2 and having some problems related to the linguistic sort, as I discovered on Oracle documentation. For example:

SELECT id, my_varchar2 from my_table ORDER BY MY_VARCHAR2;

Will return:

ID     MY_VARCHAR2
------ -----------
 3648  A
 3649  B
 6504  C
 7317  D
 3647  0

I need it to return the string "0" as the first element on this sequence, as it would be comparing ASCII values. The string can have more than one character so I can't use the ascii function as it ignores any characters except for the first one.

What's the best way to do this?

Upvotes: 4

Views: 3560

Answers (1)

Joachim Isaksson
Joachim Isaksson

Reputation: 180927

For that case, you should be able to just order by the BINARY value of your characters;

SELECT id, my_varchar2 
FROM my_table 
ORDER BY NLSSORT(MY_VARCHAR2, 'NLS_SORT = BINARY')

SQLFiddle here.

Upvotes: 6

Related Questions