Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgres natural order by

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
1.3
1.10.1
1.9

How do I sort in natural order such that when I issue SELECT version FROM TABLE_A ORDER BY version DESC it will give me

1.10.1
1.9
1.3
1.2

instead of

1.9
1.3
1.2
1.10.1
like image 644
RonPringadi Avatar asked Oct 17 '25 15:10

RonPringadi


1 Answers

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.

like image 144
Gordon Linoff Avatar answered Oct 19 '25 05:10

Gordon Linoff



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!