The Python Oracle

SQLAlchemy ORDER BY DESCENDING?

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Hypnotic Orient Looping

--

Chapters
00:00 Sqlalchemy Order By Descending?
00:30 Accepted Answer Score 454
00:41 Answer 2 Score 1061
01:06 Answer 3 Score 100
01:20 Answer 4 Score 58
02:32 Thank you

--

Full question
https://stackoverflow.com/questions/4186...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #sqlalchemy

#avk47



ANSWER 1

Score 1061


Just as an FYI, you can also specify those things as column attributes. For instance, I might have done:

.order_by(model.Entry.amount.desc())

This is handy since it avoids an import, and you can use it on other places such as in a relation definition, etc.

For more information, you can refer this SQLAlchemy 1.4 Documentation




ACCEPTED ANSWER

Score 454


from sqlalchemy import desc
someselect.order_by(desc(table1.mycol))

Usage from @jpmc26




ANSWER 3

Score 100


One other thing you might do is:

from sqlalchemy.sql import text
...
.order_by(text("name desc")

This will result in: ORDER BY name desc. The disadvantage here is the explicit column name used in order by.




ANSWER 4

Score 58


You can use .desc() function in your query just like this:

query = (model.Session.query(model.Entry)
        .join(model.ClassificationItem)
        .join(model.EnumerationValue)
        .filter_by(id=c.row.id)
        .order_by(model.Entry.amount.desc())
        )

This will order by amount in descending order or

query = session.query(
    model.Entry
).join(
    model.ClassificationItem
).join(
    model.EnumerationValue
).filter_by(
    id=c.row.id
).order_by(
    model.Entry.amount.desc()
)
)

Use of desc function of SQLAlchemy:

from sqlalchemy import desc
query = session.query(
    model.Entry
).join(
    model.ClassificationItem
).join(
    model.EnumerationValue
).filter_by(
    id=c.row.id
).order_by(
    desc(model.Entry.amount)
)
)

For official docs please use the link or check below snippet:

sqlalchemy.sql.expression.desc(column) Produce a descending ORDER BY clause element.

e.g.:

from sqlalchemy import desc

stmt = select([users_table]).order_by(desc(users_table.c.name))

will produce SQL as:

SELECT id, name FROM user ORDER BY name DESC

The desc() function is a standalone version of the ColumnElement.desc() method available on all SQL expressions, e.g.:

stmt = select([users_table]).order_by(users_table.c.name.desc())

Parameters column – A ColumnElement (e.g. scalar SQL expression) with which to apply the desc() operation.

See also

asc()

nullsfirst()

nullslast()

Select.order_by()