PostgreSQL ORDER BY issue - natural sort

前端 未结 7 1309
日久生厌
日久生厌 2020-12-01 16:38

I\'ve got a Postgres ORDER BY issue with the following table:

em_code  name
EM001    AAA
EM999    BBB
EM1000   CCC

To insert a

7条回答
  •  清歌不尽
    2020-12-01 17:08

    One approach you can take is to create a naturalsort function for this. Here's an example, written by Postgres legend RhodiumToad.

    create or replace function naturalsort(text)
        returns bytea language sql immutable strict as $f$
        select string_agg(convert_to(coalesce(r[2], length(length(r[1])::text) || length(r[1])::text || r[1]), 'SQL_ASCII'),'\x00')
        from regexp_matches($1, '0*([0-9]+)|([^0-9]+)', 'g') r;
    $f$;
    

    Source: http://www.rhodiumtoad.org.uk/junk/naturalsort.sql

    To use it simply call the function in your order by:

    SELECT * FROM employees ORDER BY naturalsort(em_code) DESC
    

提交回复
热议问题