Sql - Natural Ordering - Varchar

Asked

Viewed 180 times

3

Situation

I need to perform Natural string ordering.

Example

Processo 1
Processo 2
Processo 3
Processo 10
Processo 11
Processo 12

Standard Order. (ASC)

Processo 1
Processo 10
Processo 11
Processo 12
Processo 2
Processo 3

Natural Order

Processo 1
Processo 2
Processo 3
Processo 10
Processo 11
Processo 12

Related

PHP Natural ordering

2 answers

3


The solution I found in the OR was this

Code

ORDER BY 
    regexp_replace(column_name, '\D','','g')::integer

Explanation

It will remove from the string anything other than number, then convert to integer, after applying the integer-based ordering.

Pattern ordering example
Example natural ordering

  • If it works, create a fiddle with a testable example :)

  • @rray I got by the example = D

  • After 262728256 attempts xD sqlfiddle is complicated.

0

SELECT 
    column_name 
FROM 
    table_name 
ORDER BY
    column_name REGEXP '^\d*[^\da-z&\.\' \-\"\!\@\#\$\%\^\*\(\)\;\:\\,\?\/\~\`\|\_\-]' DESC, 
    column_name + 0, 
    column_name;

Browser other questions tagged

You are not signed in. Login or sign up in order to post.