Mysql – How to UPDATE NULL values by MAX()+1

maxMySQLupdate

I want to assign values to null cells of a column as

UPDATE table 1
SET number = MAX(number) + 1
WHERE number IS NULL

but mysql return error Invalid use of group function.

Best Answer

Assuming that you want - if the max(number) in the whole table is say, 27 - to update all the rows with NULL, to 28.

You need a subquery or a derived table to first find this max and then join back to the table:

UPDATE tableX AS t
  CROSS JOIN
    ( SELECT MAX(number) AS max_number
      FROM tableX
    ) AS m
SET t.number = m.max_number + 1
WHERE t.number IS NULL ;