Search code examples
sqlpostgresqlecto

Query returns list based on order by each field (SQL)


I want with just one query (SQl) in a table, that has multi "order by" of many fields.

I want with each "order by" of each field the query to return individual list results based on data in the table

ex:

name c1 c2
"a" 1   2
"b" 3   4
"c" 2   1
"d" 3   1
"e" 1   4
"f" 3   4
"g" 5   2
"h" 4   4

i want with one query to return 1 list based on order by "c1" and "c2" (asc) like below:

"a" 1   2 --> order asc by c1
"e" 1   4
"c" 2   1
"b" 3   4
"d" 3   1
"f" 3   4
"h" 4   4
"g" 5   2
----------

"c" 2   1 ---> order asc by c2
"d" 3   1
"a" 1   2
"g" 5   2
"b" 3   4
"e" 1   4
"f" 3   4
"h" 4   4

Solution

  • Is this what you want?

    select t.*
    from t cross join
         (values ('col1'), ('col2')) v(which)
    order by v.which,
             (case when which = 'col1' then col1 end) asc,
             (case when which = 'col2' then col2 end) asc;
    

    Note that two separate queries might be faster for two reasons:

    1. Sorting scales as O(n * ln(n)), which means that doubling the data being sorted more than doubles the time needed to sort.
    2. If you have indexes on col1 and/or col2, then the index can be used for the sorting. That is not possible with the more complex keys.