Question

I want to update a column whose value is 0 to maximum of that column (In single query).

There are lots of records with 0 value.

I am doing this:

UPDATE table SET field = (SELECT MAX(field) + 1) WHERE field = 0;

But it updates each record to same value. Can we get max value on each row update?

Was it helpful?

Solution

You seem to want to increment the value starting with the next possible value. Here is one method:

update table t cross join
       (select @rn := max(field) from table) var
    set t.field = (@rn := @rn + 1)
    where field = 0;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top