Skip to content
Advertisement

How to sort numbers last in PostgreSQL?

Found many related answers, but nothing that did this.

How to sort by numbers last:

AA
ZZ
11
55

And, preferably (but not necessary)

AA
A1
A2

PostgreSQL 11.9

Also, probably don’t want to use a regex for performance reasons. Don’t want to create an index either…

Advertisement

Answer

I think a regex is the right way to do this:

order by (col ~ 'd')::int, col

This puts first rows that contain no digit at all, then the remaining rows. Within each group, rows are sorted by ascending value.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement