Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get last record

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?

like image 373
Dmitrijs Zubriks Avatar asked Dec 18 '11 13:12

Dmitrijs Zubriks


People also ask

How do I find the last record in SQL?

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.

How do I get last 10 records in SQL?

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.

How can I get the last record from the Employee table?

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.

How do I get last 3 records in SQL?

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!!!


1 Answers

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() 
like image 174
miku Avatar answered Sep 28 '22 03:09

miku