Postgresql sorting mixed alphanumeric data

前端 未结 7 1526
无人及你
无人及你 2020-12-30 05:32

Running this query:

select name from folders order by name

returns these results:

alphanumeric
a test
test 20
test 19
test          


        
7条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-30 06:18

    You may be able to manually sort by splitting the text up in case there is trailing numerals, like so:

    SELECT * FROM sort_test
    ORDER BY SUBSTRING(text FROM '^(.*?)( \\d+)?$'),
             COALESCE(SUBSTRING(text FROM ' (\\d+)$')::INTEGER, 0);
    

    This will sort on column text, first by all characters optionally excluding an ending space followed by digits, then by those optional digits.

    Worked well in my test.

    Update fixed the string-only sorting with a simple coalesce (duh).

提交回复
热议问题