Search code examples
postgresqlselectnumericalalphabeticaldatabase-table

Sorting results in a sql query alphabetically and numerically


I want to make a SELECT from a certain table (ex. "table1") with a column (ex. "column1") which contains a letter followed by a number (ex. z98, k87, a245, a241, d7, e91, e32, b212, r101, r32)

Is there a way to make a select that sorts the results by this column alphabetically using the first letter and then ascending using the numbers that follow them ? (ex. a241, a245, b212, e32 etc.) The purpose is to fill the datatables on the user interface according to their letter from the results, like this:

datatable_A= 
241 
245

datatable_B =
212

datatable_D= 
32
91

datatable_K=
87

datatable_R=
32
101

datatable_Z=
98

Solution

  • If you mean the numbers should be treated numerically and not as string:

    create table table1 (column1 text);
    insert into table1 (column1) values
    ('z98'), ('k87'), ('a245'), ('a241'), ('d7'), ('e91'), ('e32'), ('b212'), ('r101'), ('r32')
    ;
    
    select 
        substring(column1 from 1 for 1) as datatable, 
        substring(column1 from 2)::integer as "number"
    from table1
    order by 
        datatable, 
        "number"
    ;
     datatable | number 
    -----------+--------
     a         | 241
     a         | 245
     b         | 212
     d         | 7
     e         | 32
     e         | 91
     k         | 87
     r         | 32
     r         | 101
     z         | 98
    (10 rows)