Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sqlalchemy get last X rows in order

I need to get the last X rows from a table, but in order of the ID. How could I achieve this?

like image 747
Wiz Avatar asked Sep 10 '12 03:09

Wiz


3 Answers

query = users.select().order_by(users.c.id.desc()).limit(5)  print reversed(conn.execute(query).fetchall() ) 

something like that anyway

like image 91
Joran Beasley Avatar answered Sep 23 '22 06:09

Joran Beasley


This worked for me...

c=session.query(a).order_by(a.id.desc()).limit(2)
c=c[::-1]

This solution is 10 times faster than the python slicing solution proposed by BrendanSimon.

like image 38
p699 Avatar answered Sep 24 '22 06:09

p699


I believe you can prefix the order_by parameter with a '-' to get reverse order.

query = users.select().order_by(-users.c.id.desc()).limit(5)

Also, I believe you can use python slices as an alternative to limit.

query = users.select().order_by(users.c.id.desc())[-5:]

query = users.select().order_by(-users.c.id.desc())[:5]
like image 40
BrendanSimon Avatar answered Sep 23 '22 06:09

BrendanSimon