Getting the last row of a query

Posted under » MySQL » Python on 7 Sep 2023

In Django it is easy to retrieve the last or first row of a query or filter with the .last() or .first() command.

However in normal sql query there is no equivalent which is surprising because it is very useful. Not to worry, we can still achieve this by a two step process. First by sorting and second by limiting to just one record.

An example in peewee to get the last row, hence descending order which is usually the id which auto increments.

swan = ds.select().where(ds.qid == 17).order_by(ds.id.desc()).limit(1)

web security linux ubuntu python django git Raspberry apache mysql php drupal cake javascript css AWS data