Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

conditional order by clause in sql

Tags:

sql

oracle

I have a query that should order the result in asc or desc depending upon a column value.

e.g.

if employee of type manager exists THEN order by joining_date, bith_date ASC else if employee is developer THEN order by joining_date, birth_date DESC.

I would like to achieve something like below, but can't achieve that.

ORDER BY CASE WHEN employee_type = 'm'  
              THEN joining_date, birth_date ASC;
              WHEN employee_type = 'd' 
              THEN joining_date, birth_date  DESC; 
like image 717
Ram Dutt Shukla Avatar asked Jan 30 '13 06:01

Ram Dutt Shukla


People also ask

How ORDER BY clause is used in SQL?

The ORDER BY keyword is used to sort the result-set in ascending or descending order. The ORDER BY keyword sorts the records in ascending order by default. To sort the records in descending order, use the DESC keyword.

What is conditional clause in SQL?

A "conditional clause" is a portion of a query that restricts the rows matched by certain conditions. In SQL, that means the WHERE or HAVING portions of a SELECT , UPDATE , or DELETE query. In all dynamic queries in Drupal those are implemented using the same mechanism.

What is ORDER BY 2/3 in SQL?

It stands for, Order by first column in the select list, then 2nd, then 3rd and then 4th.

Can you ORDER BY a SELECT statement?

SQL queries initiated by using a SELECT statement support the ORDER BY clause. The result of the SELECT statement is sorted in an ascending or descending order.


2 Answers

Well I got the answer after some research.

We can add multiple columns in where clause conditionally as follows :

ORDER BY DECODE(employee_type, 'm', joining_date, birth_date, salary) ASC,
         DECODE(employee_type, 'd', joining_date, birth_date, salary) DESC

This will order the result on the basis of employee_type.

like image 76
Ram Dutt Shukla Avatar answered Oct 19 '22 23:10

Ram Dutt Shukla


I suspect you want something like this:

ORDER BY 
    employee_type DESC             -- first all the managers, then the developers
                                   -- and in every one of these two groups
  , joining_date                   -- first order by joining date
  , CASE WHEN employee_type = 'm'  -- and then either by
        THEN birth_date            -- birth date ascending for managers
        ELSE NULL
    END                            -- or
  , birth_date DESC ;              -- birth date descending for the rest (devs)
like image 5
ypercubeᵀᴹ Avatar answered Oct 19 '22 21:10

ypercubeᵀᴹ