51

One field of my table's field is set to 0 for all rows. But I want to update the incremental value by step 1 in an update query.

How can I do that in mysql?

ouflak
  • 2,458
  • 10
  • 44
  • 49
hd.
  • 17,596
  • 46
  • 115
  • 165
  • To clarify: You are asking how to change an existing data set so it has incrementing numbers? – Pekka Dec 14 '10 at 12:13
  • no,i add this field recently so it is set to 0 by default and it should not be auto increment for feature.i just want to fill it with valid data.hope i could clarify it. – hd. Dec 14 '10 at 12:16

5 Answers5

121

Try this:

mysql> select @i := 0;
mysql> update bar set c = (select @i := @i + 1);
Pablo Santa Cruz
  • 176,835
  • 32
  • 241
  • 292
16
SET @a = 0;  
UPDATE customers SET id = @a:=@a+1;

You can go for this as well.

DRUPWAY
  • 345
  • 6
  • 16
7

One line solution:

UPDATE tablename AS a, (SELECT @a := 0) AS b SET a.fieldname = @a:=@a+1
mjjm
  • 73
  • 1
  • 3
3

One way is to create a new table with an AUTO_INCREMENT column instead of the original column, inserting all data from the old into the new table, and then renaming the new and deleting the old.

Another way is to run your update query with a MySQL variable that generates an increasing number for each row (to emulate the ROW_NUMBER() function found in other DBMS systems).

littlegreen
  • 7,290
  • 9
  • 45
  • 51
  • as i remember i did it before using mysql variables but i don't remember the solution at this time. ;( – hd. Dec 14 '10 at 12:19
-2

The easiest way for me is to drop the field and re-create it with auto-increment.

Paul Godard
  • 1,055
  • 1
  • 14
  • 30