Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to order by case, descending?

I want to build this query using SQLAlchemy:

select * from t order by
case
    when t.x!=0 then t.y
    when t.x==0 then 0
end desc;

I tried the following:

db.session.query(t).order_by(
    db.func.desc(
        db.func.case([
            (t.x!=0, t.y),
            (t.x==0, 0)
        ]
    )
)

But it raised a ProgrammingError 'You have an error in your SQL syntax'. How can I write this case statement in SQLAlchemy?

like image 852
Hayes Pan Avatar asked Mar 05 '15 07:03

Hayes Pan


People also ask

How do you do order by in descending?

The ORDER BY keyword is used to sort the result-set in ascending or descending order. The ORDER BY keyword sorts the records in ascending order by default. To sort the records in descending order, use the DESC keyword.

How do you use order by in case?

CASE Syntax: CASE WHEN condition1 THEN result1 WHEN condition2 THEN result2 WHEN condition3 THEN result3 ELSE result END; ORDER BY: This keyword is used to sort the result-set in ascending or descending order. It sorts the records in ascending order by default.

Can we use order by in case?

Although it is most often used there, CASE is not limited to SELECT statements. For example, you can use it in clauses like IN , WHERE , HAVING , and ORDER BY .

Is order by ascending or descending by default?

By default ORDER BY sorts the data in ascending order. We can use the keyword DESC to sort the data in descending order and the keyword ASC to sort in ascending order.


1 Answers

case is not a function, and is present on the db instance. You can specify an else clause rather than a second when. You can just call .desc() on an expression rather than wrapping it with desc(). The query should look like:

db.session.query(t).order_by(db.case(((t.x != 0, t.y),), else_=0).desc())
like image 162
davidism Avatar answered Sep 28 '22 23:09

davidism