简体   繁体   中英

Sort strings with custom order in Oracle SQL

Problem :

We first define a custom character order in the following way:

A < ... < Z  <  a < ... < z  <  0 < ... < 9  <                              <
capitals        lowercase       digits         printable special characters   space

Special characters' order is not specified, so, they can be compared arbitrarily.

Given a table INPUT with one VARCHAR2 column, sort its content (strings containing only characters listed in order definition) in lexicographic order, using the character order defined above.

Question: how can one implement such sorting in pure Oracle SQL (without using PL/SQL and undocumented functions)?

It looks like Oracle DB doesn't have a feature to use such an order directly in ORDER BY .

You could use translate() :

order by translate(col, 
                   'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789',
                   '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
                  )

This replaces the characters that you care about with the "natural" ASCII ordering of the characters.

You can use a collation at the column level. Collations specify how VARCHAR2 values are compared and sorted.

See Column Level Collation or Statement Level Collation .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM