MySQL populate new column with incrementing values without auto_increment - mysql

I see lots of almost similar questions with obvious answers but I'm fairly sure this question isn't already on here.
I need to add an auto-incrementing id column to an existing table and set it as the primary key. I can't lose any of the existing data.
I can successfully make the change to the table structure but I get an error about truncated data in the new column. When I view the data every value in the new auto-incrementing column is null (and therefore not unique).
How can I back-fill these values to ensure uniqueness in my primary key?
***I would prefer to avoid dumping the existing data to a temporary table and re-inserting if there is a simpler solution.
Current script:
alter table the_table add new_field int first;
alter table the_table drop primary key, add primary key (new_field);
alter table the_table change new_field new_field int unsigned not null auto_increment;
I run the script in this order as I can't have an auto-incrementing column that isn't the primary key.
(MySQL 5.3)

Try creating the column, setting it as primary key and auto increment in one go
ALTER TABLE `the_table` ADD `new_field` INT NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST;

Just add an auto-increment field, without being a primary key:
ALTER TABLE `the_table` ADD `new_field` INT NOT NULL AUTO_INCREMENT

Related

How can I create an AUTO_INCREMENT column in a table that already exists and has data?

I want to create a column that will auto increment when a new row is inserted.
The table has already data and this data does not need to receive this index, or it can be NULL. I just want to start to increment since now.
It looks simple, but I run in Workbench this:
ALTER TABLE `serra`.`acionamento`
ADD COLUMN `indice` INT NULL AUTO_INCREMENT AFTER `date_insercao`
... and it says
Incorrect table definition; there can be only one auto column and it must be defined as a key
This column really needs to be a primary key?
I found the solution I was looking for...
I was missing an UNIQUE configuration...
ALTER TABLE `serra`.`acionamento`
ADD COLUMN `indice` INT NOT NULL AUTO_INCREMENT AFTER `column`,
ADD UNIQUE INDEX `indice_UNIQUE` (`indice` ASC);
Thanks for the comments

How to add new column in table as primary key?

I wonder how to add new column ( set as primary key and set default value) in existing table ? I tried
ALTER TABLE table_name ADD ( column_name VARCHAR (10));
ALTER TABLE table_name ALTER COLUMN column_name SET DEFAULT 'value1';
ALTER TABLE table_name ADD PRIMARY KEY(column_name);
>> ERROR 1138 (22004): Invalid use of NULL value
I saw couple posts but it requires to delete all existing data in the table which I don't want to. Is there other way to add new column as primary key without delete data in table?
My current table:
My new table that I want to create:
Thanks
Doing this gives ERROR since whenever you add a new column in a table which already has 1 or more rows then the new column will get NULL values in all of its tuples which is contradictory to the rule which says PRIMARY KEY CAN NOT CONTAIN NULL.
Also, if you provide DEFAULT value, then also duplicate entries aren't allowed in the primary key!
So just by adding a new column in a non-empty table by giving default and declaring it primary key at the same time will not work.
Now here comes AUTO_INCREMENT to rescue, add column by incrementing and declarig it as primary key:
ALTER TABLE table_name ADD COLUMN new_column INT AUTO_INCREMENT PRIMARY
KEY ;
This works fine now...
Thanks for asking.
Your column might have Null values in it, and also try dropping the primary key constraint first if there is any.
try this DDL:
ALTER TABLE table_name ADD ( column_name VARCHAR (10) SET DEFAULT 'value1');
ALTER TABLE table_name ADD PRIMARY KEY(column_name);
Your column might have null values
If your table doesn't have a primary key and would like to add a new column and make it as a primary key, use the below query and use auto increment so it will be unique
ALTER TABLE old_table ADD pk_column INT AUTO_INCREMENT PRIMARY KEY;

Innodb doesn't let me update the composite primary key?

I'm trying to create a history table to store all historical records of its corresponding table
However, when I switch from the MyISAM to InnoDB (because of the DELETE ON CASCADE) the below query yields the error: Incorrect table definition; there can be only one auto column and it must be defined as a key
CREATE TABLE tdm_history.BATCH LIKE tdm.BATCH;
ALTER TABLE tdm_history.BATCH MODIFY COLUMN id int NOT NULL,
DROP PRIMARY KEY, ADD action VARCHAR(8) DEFAULT 'insert',
ADD revision INT NOT NULL AUTO_INCREMENT,
ADD stamp DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
ADD PRIMARY KEY (id, revision);
I expect the primary of the tdm_history.BATCH from id to be changed to the composite primary key of (id, revision).
Note that, the above query works perfectly fine when the engine is set to MyISAM
Two guesses:
Plan A: Swap the MODIFY id and the DROP PK.
Plan B: Split into two ALTERs. But I don't know where. I think the problem is that ALTER has not quite let go of the id-PK link before you replace the PK. So, at least, move the ADD PK to a second ALTER.

Assign MySQL #rowid as value

I have an existing table with lot of rows (around 10k rows) with two columns as primary keys as it is acting as middle table of many-to-many relation between two other table.
For new requirements, I need to assign add new column (say id) which must be primary key with auto increment values. I ran following queries:
ALTER TABLE `momento_distribution` ADD `id` INT( 11 ) NOT NULL FIRST;
ALTER TABLE `momento_distribution` DROP PRIMARY KEY , ADD PRIMARY KEY ( `id` );
First query run successfully but second query generated following error:
1062 - Duplicate entry '0' for key 'PRIMARY'
Reason is obvious, new column id got 0 as default value and Primary key can't have duplicate values.
Now before I can run second query, I need to set incremental value for new column like 1,2,3...
In Oracle, I know, this can be done through rowid. MySQL also have its equivalent #rowid. Can someone please suggest a query to set #rowid as column value for column id?
Please Note: This had to be done through query as I can't change 10000 rows manually.
You need to set it to AUTO_INCREMENT at the same time, that will populate it;
ALTER TABLE momento_distribution
ADD id INT NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST;
Demo here.
EDIT: If you have an existing primary key, you'll need to drop that at the same time;
ALTER TABLE momento_distribution
DROP PRIMARY KEY,
ADD id INT NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST;
Same question asked by same user differently. Refer to that question.
MySQL 1062 - Duplicate entry '0' for key 'PRIMARY'
In short,
1. Remove existing FK
2. Remove existing PK
3. Run your first query as
ALTER TABLE `momento_distribution` ADD `id` INT( 11 ) PRIMARY KEY AUTO_INCREMENT NOT NULL FIRST;
which will also assign unique number without depending on #rowid
4. Add FK to earlier columns, if needed.

How to add AUTO_INCREMENT to an existing column?

How do I add auto_increment to an existing column of a MySQL table?
I think you want to MODIFY the column as described for the ALTER TABLE command. It might be something like this:
ALTER TABLE users MODIFY id INTEGER NOT NULL AUTO_INCREMENT;
Before running above ensure that id column has a Primary index.
Method to add AUTO_INCREMENT to a table with data while avoiding “Duplicate entry” error:
Make a copy of the table with the data using INSERT SELECT:
CREATE TABLE backupTable LIKE originalTable;
INSERT backupTable SELECT * FROM originalTable;
Delete data from originalTable (to remove duplicate entries):
TRUNCATE TABLE originalTable;
To add AUTO_INCREMENT and PRIMARY KEY
ALTER TABLE originalTable ADD id INT PRIMARY KEY AUTO_INCREMENT;
Copy data back to originalTable (do not include the newly created column (id), since it will be automatically populated)
INSERT originalTable (col1, col2, col3)
SELECT col1, col2,col3
FROM backupTable;
Delete backupTable:
DROP TABLE backupTable;
More on the duplication of tables using CREATE LIKE:
Duplicating a MySQL table, indices, and data
Alter table table_name modify column_name datatype(length) AUTO_INCREMENT PRIMARY KEY
You should add primary key to auto increment, otherwise you got error in mysql.
Simply just add auto_increment Constraint In column or MODIFY COLUMN :-
ALTER TABLE `emp` MODIFY COLUMN `id` INT NOT NULL UNIQUE AUTO_INCREMENT FIRST;
Or add a column first then change column as -
1. Alter TABLE `emp` ADD COLUMN `id`;
2. ALTER TABLE `emp` CHANGE COLUMN `id` `Emp_id` INT NOT NULL UNIQUE AUTO_INCREMENT FIRST;
This worked for me in case you want to change the AUTO_INCREMENT-attribute for a not-empty-table:
1.)Exported the whole table as .sql file
2.)Deleted the table after export
2.)Did needed change in CREATE_TABLE command
3.)Executed the CREATE_TABLE and INSERT_INTO commands from the .sql-file
...et viola
I managed to do this with the following code:
ALTER TABLE `table_name`
CHANGE COLUMN `colum_name` `colum_name` INT(11) NOT NULL AUTO_INCREMENT FIRST;
This is the only way I could make a column auto increment.
INT(11) shows that the maximum int length is 11, you can skip it if you want.
Alter table table_name modify table_name.column_name data_type AUTO_INCREMENT;
eg:
Alter table avion modify avion.av int AUTO_INCREMENT;
if you have FK constraints and you don't want to remove the constraint from the table. use "index" instead of primary. then you will be able to alter it's type to auto increment
I had existing data in the first column and they were 0's.
First I made the first column nullable.
Then I set the data for the column to null.
Then I set the column as an index.
Then I made it a primary key with auto incrementing turned on. This is where I used another persons answer above:
ALTER TABLE `table_name` CHANGE COLUMN `colum_name` `colum_name` INT(11) NOT NULL AUTO_INCREMENT FIRST;
This Added numbers to all the rows of this table starting at one. If I ran the above code first it wasn't working because all the values were 0's. And making it an index was also required before making it auto incrementing.
Next I made the column a primary key.
This worked in my case , if you want to change the column attribute to auto-increment which is already having some data
1.GO to structure, select the column to want to change.
2.After selecting the column , choose primary key from the options below.
[1]: https://i.stack.imgur.com/r7w8f.png
3.Then change the column attribute to auto-increment using alter method
This is to alter the column adding PRIMARY key:
ALTER TABLE `schema_name`.`table_name`
CHANGE COLUMN `id` `id` INT(11) NOT NULL AUTO_INCREMENT ,
ADD UNIQUE INDEX `id_UNIQUE` (`id` ASC) VISIBLE,
ADD PRIMARY KEY (`id`);
I copied it from MySQL Workbench... I got curious to see if it was possible to do it all in one command. I'm a little rusty in SQL.
If you are working in an specific schema, you don't need to specify it.
The above statement will create the index, set the column as the PRIMARY KEY as well with just one query.
KEEP IN MIND: There could not be duplicated values in the same column, if there are, the statement will fail to commit.
ALTER TABLE Table name ADD column datatype AUTO_INCREMENT,ADD primary key(column);