Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple ORDER BY

enter image description here

I am totally lost in OrderBy clausules.

I need this result after ordering: ID's: 8, 5, 2, 1, 4, 6, 7, 3

Theese rules must be applicated in this order:

  • top3 = 1
  • top2 = 1
  • top1 = 1
  • By order ASC, but order "NULL" or 0 to end of line

Is there any possibility to do this ordering?

Thank you all!

like image 796
czLukasss Avatar asked Dec 01 '25 02:12

czLukasss


1 Answers

I would translate your requirement as:

order by
    top3 desc,
    top2 desc,
    top1 desc,
    nullif(`order`, 0) nulls last

The last criteria shorts by ascending order, while keeping nulls and 0 values last.

Please note that order is a reserved word in all SQL dialects, so not a good choice for a column name.

like image 147
GMB Avatar answered Dec 02 '25 17:12

GMB



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!