1

I'm working with SqlAlchemy to query a database containing a list of events. Each event has a created time and an ari (amazon resource number). There's a maximum number of records I can get back from one function call, and I want to get back the records starting with the most recent first. To do this I need to manually pass in a lambda function that sorts the records properly; documentation for the argument is here:

cols (default=None):
    A function which takes a DBObject class and returns a tuple of columns (or SQLAlchemy
    expressions) used to compare it. This overrides the default sorting behaviour.
    Example: key=lambda x: (x.created, x.ari)

As you can see, by default it sorts by x.created, then x.ari, both in ascending order. I actually need to do the opposite of this and sort by x.created, then x.ari, in descending order. Is there any way I can do this with just a lambda? Using sort() or sorted() is not really an option due to me using this pre-existing function.

Eric Hasegawa
  • 169
  • 1
  • 14
  • 1
    Does this answer your question? [SQLAlchemy ORDER BY DESCENDING?](https://stackoverflow.com/questions/4186062/sqlalchemy-order-by-descending) – Brian61354270 Jul 01 '22 at 00:12
  • Per the dupe, the SQLAlchemy expressions you seek are `desc(x.created)` and `desc(x.ari)`. See [Column Element Modifier Constructors](https://docs.sqlalchemy.org/en/14/core/sqlelement.html#column-element-modifier-constructors) from the SQLAlchemy docs. The total key function for this scenario would be `lambda x: (desc(x.created), desc(x.ari))`. – Brian61354270 Jul 01 '22 at 00:13
  • @DanielHao Using `sort/sorted` isn't possible since that would require fetching the entire database. Also, AFAIK `-x.created` isn't a valid SQLAlchemy expression – Brian61354270 Jul 01 '22 at 00:21
  • @Brian Trying that I run into an error that says ```ArgumentError: SQL expression object or string expected, got object of type instead``` - Can I only sort by strings or something? The example in the SqlAlchemy code uses it like so ``` stmt = select([users_table]).order_by(desc(users_table.c.name))``` - Do I need to access some attribute of the created column or something? – Eric Hasegawa Jul 07 '22 at 14:42

0 Answers0