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

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

Posted by: admin November 1, 2017 Leave a comment

Questions:

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?

Answers:
SELECT * 
FROM table_name
ORDER BY id DESC
LIMIT 1

Questions:
Answers:

User order by with desc order:

select * from t
order by id desc
limit 1

Questions:
Answers:

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.

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

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

example:

SELECT MAX(brand) AS brandid FROM brand_tbl

Questions:
Answers:

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