2

I am trying to update the row most recently added to my table by adding a WHERE clause and selecting the MAX 'dressingID' which is my primary key.

The function is working however it is returning every row instead of just the row with the largest ID.

Here is the query:

UPDATE Dressing set dressingCode='111' WHERE dressingID=(SELECT MAX(dressingID))

Table Name = Dressing

Primary Key = dressingID

I am trying to get a number from a QR code and pass to to the latest entry into the table, however it is updating every row for some reason, any help would be appreciated. Cheers!

phpsandqs
  • 25
  • 4

1 Answers1

2

You need to reference table:

UPDATE Dressing set dressingCode='111' 
WHERE dressingID=(SELECT d FROM ((SELECT MAX(dressingID) AS d FROM Dressing)) s);
                  -- forced materialization

db<>fiddle demo

MariaDB 10.3:

UPDATE Dressing set dressingCode='111' 
WHERE dressingID=(SELECT MAX(dressingID) AS d FROM Dressing);

db<>fiddle demo

Related: You can't specify target table for update in FROM clause


Original query has A=MAX(A) condition for single row:

UPDATE Dressing set dressingCode='111' 
WHERE dressingID=(SELECT MAX(Dressing.dressingID))
<=>
UPDATE Dressing set dressingCode='111' 
WHERE dressingID=Dressing.dressingID
-- always true for non-nullable dressingID
Lukasz Szozda
  • 162,964
  • 23
  • 234
  • 275