Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select the last record from MySQL table using SQL syntax

Tags:

sql

mysql

I have a table with several records. There is an id field. I would like to select the record with the most recent id (i.e. the highest id).

Any ideas?

like image 569
Vonder Avatar asked Apr 17 '10 17:04

Vonder


People also ask

How do I select the latest record from a table in MySQL?

In SQL Server, we can easily select the last 10 records from a table by using the “SELECT TOP” statement. The TOP clause in SQL Server is used to control the number or percentage of rows from the result. And to select the records from the last, we have to arrange the rows in descending order.

How do I get the last row of a table in SQL Server?

If the table is indexed on the sort column, then SQL will just read the last row of the table. No expensive sort or full table scan is needed. @Sri You would execute SELECT TOP 1000 * FROM table_name ORDER BY column_name DESC and should output the last 1000 records.

How do I get the latest record of each ID in SQL?

Since for each row in the subquery result MySQL will need a single fetch based on primary key, the subquery will be put first in the join and the rows will be output in the order of the ids in the subquery (if we omit explicit ORDER BY for the join)


1 Answers

SELECT *  FROM table_name ORDER BY id DESC LIMIT 1 
like image 86
codaddict Avatar answered Sep 24 '22 17:09

codaddict