Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I sort the postgres column with certain special characters?

I am trying to sort on a character column in a Postgres database:

Select column1 from table order by column1

Output

dir1 
dir2
dir3
#num1
t1

I want the sort to print #num1 first the way sqlite does. Any ideas what I need to change in my query?

like image 528
user2507190 Avatar asked Mar 24 '23 11:03

user2507190


1 Answers

A possible solution would be to "disable" your collation setting for this sort:

WITH x(a) AS (VALUES
  ('dir1')
 ,('dir2')
 ,('dir3')
 ,('#num1')
 ,('t1')
 )
SELECT *
FROM   x
ORDER  BY a COLLATE "C";

Ad-hoc Collation for individual expressions requires PostgreSQL 9.1 or later.

Most locales would ignore the leading # for sorting. If you switch to "C", characters are effectively sorted by their byte values. This may or may not be what you want, though.

Many related questions, like here:
PostgreSQL UTF-8 binary collation

like image 156
Erwin Brandstetter Avatar answered Apr 25 '23 06:04

Erwin Brandstetter