20

I am trying to update fields in my DB, but got stuck with such a simple problem: I want to update just one row in the table with the biggest id number. I would do something like that:

UPDATE table SET name='test_name' WHERE id = max(id)

Unfortunatelly it doesnt work. Any ideas?

Table Structure

id | name
---|------
 1 | ghost
 2 | fox
 3 | ghost

I want to update only last row because ID number is the greatest one.

iblue
  • 29,609
  • 19
  • 89
  • 128
Kalreg
  • 931
  • 3
  • 12
  • 31
  • http://stackoverflow.com/questions/9220497/mysql-in-php-how-to-update-only-one-row-in-table-but-with-greatest-id-num[**enter link description here**](http://stackoverflow.com/questions/9220497/mysql-in-php-how-to-update-only-one-row-in-table-but-with-greatest-id-number)ber –  Oct 15 '15 at 12:00

9 Answers9

73

The use of MAX() is not possible at this position. But you can do this:

UPDATE table SET name='test_name' ORDER BY id DESC LIMIT 1;

For multiple table, as @Euthyphro question, use table.column.
The error indicates that column id is ambiguous.

Example :

UPDATE table1 as t1
LEFT JOIN table2 as t2
       ON t2.id = t1.colref_t2
SET t1.name = nameref_t2
ORDER BY t1.id DESC
LIMIT 1
syahid246
  • 109
  • 2
  • 7
iblue
  • 29,609
  • 19
  • 89
  • 128
  • 1
    This will only work if you're using one table. If you're using alias with multiple tables in WHERE clause, it will fail with `SQL Error (1221): Incorrect usage of UPDATE and ORDER BY` – Euthyphro Dec 27 '13 at 16:56
6
UPDATE table SET name='test_name' WHERE id = (SELECT max(id) FROM table) 

This query will return an error as you can not do a SELECT subquery from the same table you're updating.

Try using this:

UPDATE table SET name='test_name' WHERE id = (
    SELECT uid FROM (
        SELECT MAX(id) FROM table AS t
    ) AS tmp
)

This creates a temporary table, which allows using same table for UPDATE and SELECT, but at the cost of performance.

Bryn
  • 61
  • 1
  • 2
4

I think iblue's method is probably your best bet; but another solution might be to set the result as a variable, then use that variable in your UPDATE statement.

SET @max = (SELECT max(`id`) FROM `table`);
UPDATE `table` SET `name` = "FOO" WHERE `id` = @max;

This could come in handy if you're expecting to be running multiple queries with the same ID, but its not really ideal to run two queries if you're only performing one update operation.

Lachlan McDonald
  • 2,195
  • 2
  • 21
  • 25
2
UPDATE table_NAME
SET COLUMN_NAME='COLUMN_VALUE' 
ORDER BY ID 
DESC LIMIT 1;

Because you can't use SELECT IN DELETE OR UPDATE CLAUSE.ORDER BY ID DESC LIMIT 1. This gives you ID's which have maximum value MAX(ID) like you tried to do. But MAX(ID) will not work.

Sebsemillia
  • 9,366
  • 2
  • 55
  • 70
Yanks
  • 173
  • 2
  • 15
1

Old Question, but for anyone coming across this you might also be able to do this:

UPDATE
     `table_name` a
JOIN (SELECT MAX(`id`) AS `maxid` FROM `table_name`) b ON (b.`maxid` = a.`id`)
SET a.`name` = 'test_name';
WaveTyler
  • 11
  • 1
0

We can update the record using max() function and maybe it will help for you.

 UPDATE MainTable
 SET [Date] = GETDATE()
 where [ID] = (SELECT MAX([ID]) FROM MainTable)

It will work the perfect for me.

kishan Radadiya
  • 788
  • 6
  • 14
0

I have to update a table with consecutive numbers.

This is how i do.


UPDATE pos_facturaciondian fdu 
            SET fdu.idfacturacompra = '".$resultado["afectados"]."', 
            fdu.fechacreacion = '".$fechacreacion."'
            WHERE idfacturaciondian = 
            (
                SELECT min(idfacturaciondian) FROM 
                (   
                    SELECT * 
                    FROM pos_facturaciondian fds
                    WHERE fds.idfacturacompra = ''
                    ORDER BY fds.idfacturaciondian
                ) as idfacturaciondian
            )
-2

Using PHP I tend to do run a mysqli_num_rows then put the result into a variable, then do an UPDATE statement saying where ID = the newly created variable. Some people have posted there is no need to use LIMIT 1 on the end however I like to do this as it doesn't cause any trivial delay but could prevent any unforeseen actions from being taken.

If you have only just inserted the row you can use PHP's mysqli_insert_id function to return this id automatically to you without needing to run the mysqli_num_rows query.

iblue
  • 29,609
  • 19
  • 89
  • 128
Andrew
  • 19
  • 1
-6

Select the max id first, then update.

UPDATE table SET name='test_name' WHERE id = (SELECT max(id) FROM table)

Muhammad Abrar
  • 2,292
  • 1
  • 15
  • 13
  • 7
    This will fail with MySQL error #1093: `You can't specify target table 'table' for update in FROM clause`. MySQL does not support updating a table while reading from it with a subquery. – iblue Feb 09 '12 at 23:37
  • 12
    I do not understand why people would downvote this so badly. It requires only a small fix for MySQL: `UPDATE table SET name='test_name' WHERE id = (SELECT max(id) FROM (SELECT * FROM table))`. It's also good habit to leave comment when you decide to downvote so that a responder knows how to improve the answer. – luqo33 Jun 08 '16 at 07:51