Home > Mobile >  How to sort alphanumeric strings Lexicographically in Postgres
How to sort alphanumeric strings Lexicographically in Postgres

Time:08-18

We have a column in a PostgreSQL table with the following data:

1A
1ABCD
1B
ABCD1
2
ABCD2
3
ABCD3
ABCD4
ABCD5
ABCD10
ABCD11
ABCD1111
A
B 

Expected result after sorting:

1
2
3
1A
1ABCD
1B
A
B
ABCD1
ABCD2
ABCD3
ABCD4
ABCD5
ABCD10
ABCD11
ABCD1111

We tried doing normal DESC and '([0-9] )')::BIGINT ASC. But not getting expected sorted results.

CodePudding user response:

So you can try this just put column name instead of asterisk and column.

SELECT * FROM PostgreSQL ORDER BY column ASC;

CodePudding user response:

Mike O's comment is correct if you have a typo in where you would like B sorted in the mix. However, if you have some complex logic (ie, not truly lexicographical order) and you really want B sorted before ABCD1, then you could use a case statement to help your sorts:

select col1, 
case 
  when col1 ~* '[a-z]' is false then 1 --numeric only
  when substring(col1, 1, 1) ~* '[0-9]' is true then 2 --starts with number
  when col1 ~* '[0-9]' is false then 3 --letters only
  else 4 --alphanumeric mixed
end sort1
from my_table
order by 2,1

Output:

col1 sort1
1 1
2 1
3 1
1A 2
1ABCD 2
1B 2
A 3
B 3
ABCD1 4
ABCD10 4
ABCD11 4
ABCD1111 4
ABCD2 4
ABCD3 4
ABCD4 4
ABCD5 4

DB-fiddle found here.

  • Related