Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Oracle: How can I implement a "natural" order-by in a SQL query?

Tags:

sql

oracle

e.g,

foo1
foo2
foo10
foo100

rather than

foo1
foo10
foo100
foo2

Update: not interested in coding the sort myself (although that's interesting in its own right), but having the database to do the sort for me.

like image 502
Mark Harrison Avatar asked Oct 20 '08 21:10

Mark Harrison


People also ask

Can we use ORDER BY in subquery in Oracle?

Order by clause does not works inside a Sub-Query.No use of giving ORDER BY clause inside the sub query. Subquery gives values to the outer query and outer query only orders the value based on the order by clause.

How do I order chronologically in SQL?

The ORDER BY keyword sorts the records in ascending order by default. To sort the records in descending order, use the DESC keyword.

What is default ordering in SQL?

The default order is ascending. The SQL ORDER BY clause is used with the SQL SELECT statement. Note: SQL ORDER BY clause always come at the end of a SELECT statement.

What is ORDER BY in Oracle SQL?

An ORDER BY clause allows you to specify the order in which rows appear in the result set.


1 Answers

You can use functions in your order-by clause. In this case, you can split the non-numeric and numeric portions of the field and use them as two of the ordering criteria.

select * from t
 order by to_number(regexp_substr(a,'^[0-9]+')),
          to_number(regexp_substr(a,'[0-9]+$')),
          a;

You can also create a function-based index to support this:

create index t_ix1
    on t (to_number(regexp_substr(a, '^[0-9]+')),
          to_number(regexp_substr(a, '[0-9]+$')), 
          a);
like image 83
Mark Harrison Avatar answered Nov 09 '22 19:11

Mark Harrison