How to order by a VARCHAR column lexicographically

The default order by of VARCHAR columns in Oracle is not lexicographic.
For example when I execute the query:

select * from
  (select 'a' from dual) union all
  (select '/a' from dual) union all
  (select '/b' from dual) union all
  (select '_b' from dual) union all
  (select '_a' from dual) union all
  (select 'b' from dual)
  order by 1

I will get the following result:


While in a lexicographic order by I will expect:


Is there a way to make the order by compare lexicographically?
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Jinesh KamdarCommented:
When I run it, I get it exactly the way u expect it!
SQL> select * from 
  2    (select 'a' from dual) union all
  3    (select '/a' from dual) union all
  4    (select '/b' from dual) union all
  5    (select '_b' from dual) union all
  6    (select '_a' from dual) union all
  7    (select 'b' from dual)
  8    order by 1;
6 rows selected.

Open in new window

ElishaMosheAuthor Commented:
You are right...
I found out that the cause for the problem is JDBC and I used a JDBC sql editor thats why I thought the problem was in the DB.

For some reason when using JDBC the NLS_SORT value is not BINARY while the default value in the database is BINARY. This causes the order by to display the results as shown above.

This can be fixed by altering the session of the JDBC connection:
alter session set nls_sort = BINARY;

or by modifiying the order by clause and adding NLS_SORT=BINARY, for example:

select b.a as ba from
  ((select 'a' as a from dual) union all
  (select '/a' as a from dual) union all
  (select '/b' as a from dual) union all
  (select '_b' as a from dual) union all
  (select '_a' as a from dual) union all
  (select 'b' as a from dual)) b
  order by NLSSORT(ba, 'NLS_SORT=BINARY')

Thank you.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Oracle Database

From novice to tech pro — start learning today.