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

SqlMysql

Sql Problem Overview


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?

Sql Solutions


Solution 1 - Sql

SELECT * 
FROM table_name
ORDER BY id DESC
LIMIT 1

Solution 2 - Sql

You could also do something like this:

SELECT tb1.* FROM Table tb1 WHERE id = (SELECT MAX(tb2.id) FROM Table tb2);

Its useful when you want to make some joins.

Solution 3 - Sql

User order by with desc order:

select * from t
order by id desc
limit 1

Solution 4 - Sql

SELECT MAX("field name") AS ("primary key") FROM ("table name")

example:

SELECT MAX(brand) AS brandid FROM brand_tbl

Solution 5 - Sql

SELECT   *
FROM     table
ORDER BY id DESC
LIMIT    0, 1

Solution 6 - Sql

I have used the following two:

1 - select id from table_name where id = (select MAX(id) from table_name)
2 - select id from table_name order by id desc limit 0, 1

Solution 7 - Sql

SELECT * FROM your_table ORDER BY id ASC LIMIT 0, 1

The ASC will return resultset in ascending order thereby leaving you with the latest or most recent record. The DESC counterpart will do the exact opposite. That is, return the oldest record.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionVonderView Question on Stackoverflow
Solution 1 - SqlcodaddictView Answer on Stackoverflow
Solution 2 - SqlLuiz VidView Answer on Stackoverflow
Solution 3 - SqlAndrew BezzubView Answer on Stackoverflow
Solution 4 - SqlNikko DomingoView Answer on Stackoverflow
Solution 5 - SqlyassinView Answer on Stackoverflow
Solution 6 - SqlSafeer AhmedView Answer on Stackoverflow
Solution 7 - SqlJDK BenView Answer on Stackoverflow