views:

181

answers:

3

How to set conditional logic in SQL query in order to shuffle the precedence?

For example if I have table with columns like "id", "name", "event_id" and I have distinct "event_id" like 180, 181, 270, 271 and I need to order in such a way that rows with "event_id" 270 will be at the top, then rows with "even_id" 271 and the rest of the data will be ordered by "id" column in descending order.

+9  A: 

use CASE statement to do order you want

ORDER BY
CASE
    WHEN event_id = 270 THEN 0
    WHEN event_id = 271 THEN 1
    ELSE 2
END,
id DESC
zerkms
That is the same comment I was in the process of writing :)
Jackson Miller
@Jackson Miller:i will be surprised if there is another such elegant solution ;-)
zerkms
+3  A: 

I prefer CASE:

ORDER BY CASE event_id WHEN 270 THEN 0
                       WHEN 271 THEN 1
         END NULLS LAST,
         id DESC;

but sometimes I use DECODE which is a little less wordy:

ORDER BY DECODE(event_id, 270, 0,
                          271, 1,
                          2),
         id DESC;
Jeffrey Kemp
A: 

Here's a simple way if you only have one case:

ORDER BY event_id <> 270 ASC, event_id ASC

The expression event_id <> 270 evaluates to 0 for false or 1 for true.

Marcus Adams
Oracle does not support boolean expressions in the ORDER BY clause.
Jeffrey Kemp