Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does PostgreSQL order textual values?

The following query

SELECT * FROM (VALUES('c'), ('a'), ('b'), ('"a"')) X ORDER BY 1 ASC

produces

a
"a"
b
c

So how come does "a" appear after a even though it starts with a non alphabetic character (ie ") ?

I thought the output should be

"a"
a
b
c

It seems like PostgreSQL is stripping non alphabetic characters while sorting those values but that does't make sense to me.

like image 771
Muhammad Gelbana Avatar asked Jan 24 '26 22:01

Muhammad Gelbana


1 Answers

Sort behaviour of text (char, varchar, text) depends on the current collation of your locale. Try using,

SELECT * 
FROM (VALUES('c'), ('a'), ('b'), ('"a"')) X(col) 
ORDER BY col COLLATE "C" asc;

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

like image 109
a_good_human Avatar answered Jan 27 '26 15:01

a_good_human



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!