I need to add an auto increment id to an already existing table. I did:
ALTER TABLE table_name ADD column_name INT NOT NULL AUTO_INCREMENT FIRST ,
ADD PRIMARY KEY (column_name)
However, the auto numbering wasnt based on any particular column order. I want mysql to smartly put auto numbers based on the order of certain column. Is it possible?
Most of the answers out there tell you how to add auto increment fields, not how to control those numbers in already existing table.
Note that MySQL table can only have one column with AUTO_INCREMENT
attribute.
Assuming the table doesn't have a primary key:
ALTER TABLE table_name ADD COLUMN new_id INT NOT NULL;
SET @x = 0;
UPDATE table_name SET new_id = (@x:=@x+1) ORDER BY whateveryouwant ASC;
ALTER TABLE table_name ADD PRIMARY KEY new_id (new_id);
ALTER TABLE table_name CHANGE new_id new_id INT NOT NULL AUTO_INCREMENT;
Assuming the table already has a NON-incremented primary key:
Just ommit the PRIMARY
keyword in the fourth command.