MySQL : how to get last N records using query. | Sololearn: Learn to code for FREE!
Novo curso! Todo programador deveria aprender IA generativa!
Experimente uma aula grƔtis
+ 2

MySQL : how to get last N records using query.

Using offset X; will help to exclude first X recods but what to do if we dont know how many records are there in table. Is there any query to know number of records?

19th Nov 2022, 10:17 AM
Sunil Shrestha
Sunil Shrestha - avatar
6 Respostas
+ 5
First way: SELECT * FROM tableName ORDER BY columnName DESC LIMIT 1; Second way: SET @variableName = (SELECT MAX(columnName) FROM tableName); SELECT *FROM tableName WHERE columnName = @variableName;
19th Nov 2022, 12:09 PM
JaScript
JaScript - avatar
+ 4
Supposing that you mean last inserted records and every records has some key that correlates to time insertion (example classic id) you can solve very simply by ording in descendig order and limit the results.. Ex. SELECT * FROM users ORDER BY id DESC LIMIT 10 where users table has a autoincrement primary key id
19th Nov 2022, 12:09 PM
KrOW
KrOW - avatar
+ 3
Sunil Shrestha beware that running the same query twice may return records in a different order unless you explicitly sort them. So be sure to include ORDER BY in your query. To get the bottom N records, sort in reverse order and take the top N by using LIMIT. If you need the bottom N to be in a forward order, then use the above query as a subquery and apply ORDER BY again to sort the results of the subquery. SELECT * FROM (SELECT * FROM... ORDER BY ... LIMIT @N) ORDER BY .... If you need to know the total number of records you can use the count() function: SELECT count(*) FROM mytable.
19th Nov 2022, 3:38 PM
Brian
Brian - avatar
+ 3
20th Nov 2022, 3:27 AM
Sunil Shrestha
Sunil Shrestha - avatar
+ 2
or is there any query for last N recods using limit
19th Nov 2022, 10:18 AM
Sunil Shrestha
Sunil Shrestha - avatar
0
you can use the primary key
19th Nov 2022, 11:10 AM
Giannis
Giannis - avatar