Postgres natural order by

后端 未结 2 795
夕颜
夕颜 2021-01-15 15:52

I have a sorting issue in postgres in a column with values such as version. Version is character varying, with values such as the following (un-ordered).

1.2         


        
2条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-15 16:18

    Postgres allow you to sort by arrays -- which is essentially what the version number represents. Hence, you can use this syntax:

    order by string_to_array(version, '.')::int[] desc
    

    Here is a full example:

    select *
    from (values ('1'), ('2.1'), ('1.2.3'), ('1.10.6'), ('1.9.4')) v(version)
    order by string_to_array(version, '.')::int[] desc;
    

    And even a demonstration.

提交回复
热议问题