ORDER BY with Case-Statement DESC

  • Like ORDER BY with CASE -Statement
    • first group: null values ​​in the Col1 date column Col2 DESC date column
    • second group: non-zero values ​​in date-column- Col1 , sorted by Col1 DESC

I tried the following:

 SELECT columns FROM tables WHERE condition ORDER BY case when Table1.Col1 IS NULL then 0 end, Table2.Col2 DESC, case when Table1.Col1 IS NOT NULL then 1 end, Table1.Col1 DESC 

But the sort order is wrong, first NOT NULL values ​​(sorted by Col2 instead of Col1). I think I missed the detail.

+6
source share
2 answers
 SELECT columns FROM tables WHERE condition ORDER BY case when Table1.Col1 IS NULL then 0 else 1 end ASC ,case when Table1.Col1 IS NULL then Table2.Col2 else Table1.Col1 end DESC 
+7
source

This should work - just make the first column 0 or 1 depending on whether it is null or not:

 SELECT columns FROM tables WHERE condition ORDER BY case when Table1.Col1 IS NULL then 0 else 1 end, case when Table1.Col1 IS NULL then Table1.Col2 else Table1.Col1 end 
+4
source

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


All Articles