Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostgreSQL Sort

I have a sort problem in PostgreSQL with below data:

name
-----
@CF
@CG
CD
CE

I used select name from table order by name, the result as below:

name
-----
CD
CE
@CF
@CE

It seems that Postgres just ignores the special character @ and sorts the left string. However, I'd like it sorted like this:

name
-----
@CF
@CG
CD
CE

Searching the internet didn't help. I hope someone here could give a suggestion.

like image 538
Damon Avatar asked Sep 12 '25 21:09

Damon


2 Answers

Use PostgreSQL's collation support to tell it you want a particular collation.

Given:

CREATE TABLE t AS VALUES ('CD'),('CE'),('@CF'),('@CE');

You can force byte-wise collation using:

SELECT * FROM t ORDER BY column1 COLLATE "C";

The "C" collation is a byte-wise collation that ignores national language rules, encoding, etc.

like image 138
Craig Ringer Avatar answered Sep 15 '25 10:09

Craig Ringer


Just add that to the order by clause:

ORDER BY CASE WHEN LEFT(name,1) = '@' THEN 0 ELSE 1 END ASC, name ASC
like image 21
PinnyM Avatar answered Sep 15 '25 10:09

PinnyM