Question

i am trying to add incremented values to a new column in table. Here is a sample structure of table

---------------------
Name - class - id
---------------------
abbc - 2     - null
efg  - 4     - null
ggh  - 6     - null
---------------------

i want to write a query that will generate unique id's for all records in table Here is the query i have tried but show null

set @i=0;
update table1 set id =(@i:=@i+1);
Was it helpful?

Solution

What you have shown should work; the id column should be getting assigned values.

I tested your statement; I verified it works on my database. Here's the test case I ran:

CREATE TABLE table1 (`name` VARCHAR(4), class TINYINT, id INT);
INSERT INTO table1 (`name`,class) VALUES ('abbc',2),('efg',4),('ggh',6);
SET @i=0;
UPDATE table1 SET id =(@i:=@i+1);
SELECT * FROM table1;

Note that MySQL user variables are specific to a database session. If the SET is running in one session, and the UPDATE is running another session, that would explain the behavior you are seeing. (You didn't mention what client you ran the statements from; most clients reuse the same connection, and don't churn connections for each statement, I'm just throwing that out as a possibility.)

To insure that @i variable is actually initialized when the UPDATE statement runs, you can do the initialization in the UPDATE statement by doing something like this:

UPDATE table1 t
 CROSS
  JOIN (SELECT @i := 0) s
   SET t.id =(@i:=@i+1);

I tested that, and that also works on my database.

OTHER TIPS

try this query my friend:

set @i=0;
update table1 set id =(select @i:=@i+1);

SQL Fiddle

SET @a = 0;  
UPDATE table_name SET id = @a:=@a+1;

Use AUTOINCREMENT parameter for the respective column instead. This parameter will put an unique auto incremented value in the respective column.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top