Sort alphanumeric data in Oracle

I have alphanumeric data like:

1
1a
1b
2
2b
10
10a

If I sort this data, the output will look like this:

1
1a
10
10a
2
2b

But I want a conclusion like:

1
1a
2
2b
10
10a

How to get this output using Oracle command?

+3
source share
2 answers

So, as I understand it, you want to sort by the numerical part of your data. To do this, you can use the regular expression (to extract the numeric part) as follows:

SQL> select str from
  2  (
  3  select '1' str from dual union all
  4  select '1a'  from dual union all
  5  select '1b'  from dual union all
  6  select '2' from dual union all
  7  select '2b'  from dual union all
  8  select '10'  from dual union all
  9  select '10a' from dual
 10  ) t
 11  order by to_number(regexp_substr(str, '^[[:digit:]]*')), str
 12  /

STR
---
1
1a
1b
2
2b
10
10a
+9
source

You can also do the same by separating the numerical and alphanumeric sort order in the order by condition. example below:

SELECT tt.qdef_grid
       FROM qgdm_qdef tt 
       ORDER BY to_number(substr(tt.qdef_grid,2,2)), substr(tt.qdef_grid,1,1);
0
source

Source: https://habr.com/ru/post/1659411/


All Articles