I need to get last record from db. I'm using sqlalchemy. At the moment, i'm doing like that:
obj = ObjectRes.query.all() return str(obj[-1].id)
But it's too heavy query. How can i get last record better?
To get the last record, the following is the query. mysql> select *from getLastRecord ORDER BY id DESC LIMIT 1; The following is the output. The above output shows that we have fetched the last record, with Id 4 and Name Carol.
Let us now implement the above query. mysql> SELECT * FROM ( -> SELECT * FROM Last10RecordsDemo ORDER BY id DESC LIMIT 10 -> )Var1 -> -> ORDER BY id ASC; The following is the output that displays the last 10 records. We can match both records with the help of the SELECT statement.
We can use the ORDER BY statement and LIMT clause to extract the last data. The basic idea is to sort the sort the table in descending order and then we will limit the number of rows to 1. In this way, we will get the output as the last row of the table. And then we can select the entry which we want to retrieve.
Try only this:- SELECT * FROM reset ORDER BY ASC LIMIT (FOUND_ROWS() - 3), 3 and check if it is giving the last 3 rows from your table in ascending order!!!
Take a look at Query.first()
. If you specify a sort on the right column, the first will be your last. An example could look like this:
obj = session.query(ObjectRes).order_by(ObjectRes.id.desc()).first()
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