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?
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.
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.
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 .
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.
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())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With