247

How can I SELECT the last row in a MySQL table?

I'm INSERTing data and I need to retrieve a column value from the previous row.

There's an auto_increment in the table.

esqew
  • 42,425
  • 27
  • 92
  • 132
  • 8
    Define "last row". The one with the highest ID? Or the most recently added one? – EboMike Nov 01 '10 at 23:21
  • 1
    What indicates the last row - Is there an auto_increment or DATETIME column in the table? – OMG Ponies Nov 01 '10 at 23:21
  • Yes, there's an `auto_increment` in there. I'd like the most recently added one. – esqew Nov 01 '10 at 23:21
  • 10
    There is no last row in a set, as EboMike and OMG Ponies said. What would you do if I'd give you a bag full of balls and ask you to give me the last ball? – Vincent Savard Nov 01 '10 at 23:22
  • The problem with the "bag full of balls" analogy is that you can "SELECT * FROM tablename LIMIT 1" and it gives you the first row in the set. If there's a first ball in the bag there should also be a last. – SkippyFlipjack Apr 11 '23 at 23:09

11 Answers11

506

Yes, there's an auto_increment in there

If you want the last of all the rows in the table, then this is finally the time where MAX(id) is the right answer! Kind of:

SELECT fields FROM table ORDER BY id DESC LIMIT 1;
Pekka
  • 442,112
  • 142
  • 972
  • 1,088
37

Keep in mind that tables in relational databases are just sets of rows. And sets in mathematics are unordered collections. There is no first or last row; no previous row or next row.

You'll have to sort your set of unordered rows by some field first, and then you are free the iterate through the resultset in the order you defined.

Since you have an auto incrementing field, I assume you want that to be the sorting field. In that case, you may want to do the following:

SELECT    *
FROM      your_table
ORDER BY  your_auto_increment_field DESC
LIMIT     1;

See how we're first sorting the set of unordered rows by the your_auto_increment_field (or whatever you have it called) in descending order. Then we limit the resultset to just the first row with LIMIT 1.

Daniel Vassallo
  • 337,827
  • 72
  • 505
  • 443
36

You can combine two queries suggested by @spacepille into single query that looks like this:

SELECT * FROM `table_name` WHERE id=(SELECT MAX(id) FROM `table_name`);

It should work blazing fast, but on INNODB tables it's fraction of milisecond slower than ORDER+LIMIT.

vzr
  • 646
  • 7
  • 13
  • 1
    @karthikeyan wrote his answer four days ago and I answered this in Dec 2015. – vzr Jun 18 '16 at 12:45
  • nope, me edited and corrected some spellings 4 days ago... post date is 2014 `answered Jun 14 at 9:41` thats about 1 year and 6 month earlier :) – Dwza Jun 21 '16 at 09:57
  • 2
    Just to clear the air here vzr is right. The 'Jun 14' means Jun 14, 2016 also @karthikeyan has only been a member for two months at this point. – Robert Brisita Aug 19 '16 at 18:23
  • 1
    Ssooo... @karthikeyan's answer is a copy of this one! – Cliff Burton Apr 12 '17 at 15:01
26

on tables with many rows are two queries probably faster...

SELECT @last_id := MAX(id) FROM table;

SELECT * FROM table WHERE id = @last_id;
spacepille
  • 4,071
  • 2
  • 15
  • 5
11

Almost every database table, there's an auto_increment column(generally id )

If you want the last of all the rows in the table,

SELECT columns FROM table ORDER BY id DESC LIMIT 1;

OR

You can combine two queries into single query that looks like this:

SELECT columns FROM table WHERE id=(SELECT MAX(id) FROM table);
Sani Kamal
  • 1,208
  • 16
  • 26
8

Make it simply use: PDO::lastInsertId

http://php.net/manual/en/pdo.lastinsertid.php

macio.Jun
  • 9,647
  • 1
  • 45
  • 41
  • 4
    Right. Most decent MySQL interface libraries have dedicated methods for this, however this question wasn't tagged PHP but general MySQL syntax. – vzr Apr 12 '17 at 13:26
8

Many answers here say the same (order by your auto increment), which is OK, provided you have an autoincremented column that is indexed.

On a side note, if you have such field and it is the primary key, there is no performance penalty for using order by versus select max(id). The primary key is how data is ordered in the database files (for InnoDB at least), and the RDBMS knows where that data ends, and it can optimize order by id + limit 1 to be the same as reach the max(id)

Now the road less traveled is when you don't have an autoincremented primary key. Maybe the primary key is a natural key, which is a composite of 3 fields... Not all is lost, though. From a programming language you can first get the number of rows with

SELECT Count(*) - 1 AS rowcount FROM <yourTable>;

and then use the obtained number in the LIMIT clause

SELECT * FROM orderbook2
LIMIT <number_from_rowcount>, 1

Unfortunately, MySQL will not allow for a sub-query, or user variable in the LIMIT clause

Ilia Gilmijarow
  • 1,000
  • 9
  • 11
6

If you want the most recently added one, add a timestamp and select ordered in reverse order by highest timestamp, limit 1. If you want to go by ID, sort by ID. If you want to use the one you JUST added, use mysql_insert_id.

EboMike
  • 76,846
  • 14
  • 164
  • 167
3

You can use an OFFSET in a LIMIT command:

SELECT * FROM aTable LIMIT 1 OFFSET 99

in case your table has 100 rows this return the last row without relying on a primary_key

Benvorth
  • 7,416
  • 8
  • 49
  • 70
1

Without ID in one query:

SELECT * FROM table_name LIMIT 1 OFFSET (SELECT COUNT(*) - 1 FROM table_name)
  • "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(SELECT COUNT(*) - 1 FROM table_name)' at line 1" – Muhammad Sulaiman Feb 02 '23 at 08:49
-2
SELECT * FROM adds where id=(select max(id) from adds);

This query used to fetch the last record in your table.

Dwza
  • 6,494
  • 6
  • 41
  • 73