Sort PostgreSQL in alphabetical and numeric ascending order

Asked 2 years ago, Updated 2 years ago, 53 views

I'd like to sort PostgreSQL version 9.3 with ascending alphabetic characters and ascending numeric characters.
Is there a way?

0001
0003
0010
a001
d001
k001
i001
z001

↓ If I do ORDER BY, I would like to sort it below. Is there any way?

a001
d001
i001
k001
z001
0001
0003
0010

postgresql

2022-09-30 18:46

1 Answers

create table mytable(
  mycolumn char(4)
);

insert into mytable (mycolumn) values 
('0001'), ('0003'), ('0010'), ('a001'), ('d001'), ('k001'), ('i001'), ('z001');

If the first character is a number, the sorting order is lower than that of alphabetic characters, how about setting the following order by:

 select * from mytable
order by case when mycolumn~'^\d'then2 else1end, mycolumn;

Results:

mycolumn 
----------
 a001
 d001
 i001
 k001
 z001
 0001
 0003
 0010
(8 rows)


2022-09-30 18:46

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.