Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL - ORDER BY, CASE and DESC

Tags:

mysql

I have a PHP variable called $var. I want to sort my result in dependence of $var. This one works:

$sql = "
SELECT
    myText1,
    myText2,
    someNumber
FROM myTable
ORDER BY
    CASE
        WHEN $var = 1 THEN myText1
        WHEN $var = 2 THEN myText2
        WHEN $var = 3 THEN someNumber
    END";

But when $var is 3 I need to sort by someNumber with DESC. So I tried this:

$sql = "
SELECT
    myText1,
    myText2,
    someNumber
FROM myTable
ORDER BY
    CASE
        WHEN $var = 1 THEN myText1
        WHEN $var = 2 THEN myText2
        WHEN $var = 3 THEN someNumber DESC
    END";

This one throws a syntax error. How can I achieve this?

like image 421
MrPeperonny Avatar asked Dec 10 '25 12:12

MrPeperonny


1 Answers

Split this into three case expressions:

ORDER BY (CASE WHEN $var = 1 THEN myText1 END) ASC,
         (CASE WHEN $var = 2 THEN myText2 END) ASC,
         (CASE WHEN $var = 3 THEN someNumber END) DESC

The ASC is optional, of course -- there just to contract with the DESC.

More importantly, this removes the automatic conversion. A CASE expression returns only one type. When you mix different types, then some sort of conversion takes place. That conversion can affect the ordering of the values. This fixes that problem.

like image 164
Gordon Linoff Avatar answered Dec 12 '25 07:12

Gordon Linoff



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!