Alphanumeric case in-sensitive sorting in postgres

前端 未结 6 1157
青春惊慌失措
青春惊慌失措 2020-12-17 09:33

I am new to postrges and want to sort varchar type columns. want to explain the problem with with below example:

table name: testsorting

   order             


        
6条回答
  •  执念已碎
    2020-12-17 10:13

    Answer strongly inspired from this one.
    By using a function it will be easier to keep it clean if you need it over different queries.

    CREATE OR REPLACE FUNCTION alphanum(str anyelement)
       RETURNS anyelement AS $$
    BEGIN
       RETURN (SUBSTRING(str, '^[^0-9]*'),
          COALESCE(SUBSTRING(str, '[0-9]+')::INT, -1) + 2000000);
    END;
    $$ LANGUAGE plpgsql IMMUTABLE;
    

    Then you could use it this way:

    SELECT name FROM testsorting ORDER BY alphanum(name);
    

    Test:

    WITH x(name) AS (VALUES ('b'), ('B'), ('a'), ('a1'),
       ('a11'), ('a2'), ('a20'), ('A'), ('a19'))
    SELECT name, alphanum(name) FROM x ORDER BY alphanum(name);
    
     name |  alphanum   
    ------+-------------
     a    | (a,1999999)
     A    | (A,1999999)
     a1   | (a,2000001)
     a2   | (a,2000002)
     a11  | (a,2000011)
     a19  | (a,2000019)
     a20  | (a,2000020)
     b    | (b,1999999)
     B    | (B,1999999)
    

提交回复
热议问题