How to set conditional logic in SQL query to shuffle priority?

How to set conditional logic in SQL query to shuffle priority?

For example, if I have a table with columns like "id", "name", "event_id", and I have a separate "event_id", such as 180, 181, 270, 271, and I need to order so that the 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 column "id" in descending order.

+4
source share
3 answers

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 verbose:

 ORDER BY DECODE(event_id, 270, 0, 271, 1, 2), id DESC; 
+8
source

use the CASE statement for the order you want

 ORDER BY CASE WHEN event_id = 270 THEN 0 WHEN event_id = 271 THEN 1 ELSE 2 END, id DESC 
+13
source

Here is an easy way if you have only 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.

0
source

Source: https://habr.com/ru/post/1303628/


All Articles