61

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?

Sébastien
  • 11,860
  • 11
  • 58
  • 78
Vonder
  • 4,033
  • 15
  • 44
  • 61

7 Answers7

140
SELECT * 
FROM table_name
ORDER BY id DESC
LIMIT 1
codaddict
  • 445,704
  • 82
  • 492
  • 529
12

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.

Luiz Vid
  • 121
  • 1
  • 2
8

User order by with desc order:

select * from t
order by id desc
limit 1
Andrew Bezzub
  • 15,744
  • 7
  • 51
  • 73
  • You forgot that OP said wanted "the" record with highest id -- should have used limit. – MJB Apr 17 '10 at 17:16
3
SELECT MAX("field name") AS ("primary key") FROM ("table name")

example:

SELECT MAX(brand) AS brandid FROM brand_tbl
James Webster
  • 31,873
  • 11
  • 70
  • 114
2
SELECT   *
FROM     table
ORDER BY id DESC
LIMIT    0, 1
yassin
  • 6,529
  • 7
  • 34
  • 39
1

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
Safeer Ahmed
  • 587
  • 6
  • 14
0
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.

pushkin
  • 9,575
  • 15
  • 51
  • 95
JDK Ben
  • 211
  • 2
  • 5