Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 652
Roman Kagan Avatar asked Nov 29 '22 18:11

Roman Kagan


2 Answers

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
like image 195
zerkms Avatar answered Dec 06 '22 16:12

zerkms


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;
like image 33
Jeffrey Kemp Avatar answered Dec 06 '22 17:12

Jeffrey Kemp