PostgreSQL Sort

后端 未结 4 657
执笔经年
执笔经年 2020-12-07 03:45

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

相关标签:
4条回答
  • 2020-12-07 04:14

    Just add that to the order by clause:

    ORDER BY CASE WHEN LEFT(name,1) = '@' THEN 0 ELSE 1 END ASC, name ASC
    
    0 讨论(0)
  • 2020-12-07 04:25

    Use this:

    SELECT name
          FROM table 
         ORDER BY name WHEN LEFT(name, 1) = '@' 
                       THEN 0 ELSE 1 END, name
    
    0 讨论(0)
  • 2020-12-07 04:26

    Your undisclosed collation setting obviously ignores the @ character for sort order. Either switch to another collation as suggested by @Craig. Or, if you want to stick to your collation for the rest of the string, add a special case for leading @.

    In Postgres you can order by boolean values directly. Default order is FALSE, TRUE, NULL.

    ORDER BY name !~~ '@%', name
    

    !~~ being the Postgres shorthand for NOT LIKE.

    0 讨论(0)
  • 2020-12-07 04:32

    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.

    0 讨论(0)
提交回复
热议问题