Add an Auto increment column that isnt a primary key SQL - mysql

I have a table that keeps track of files on a disk. I have the file path set as the primary key since this is the unique piece of data. I want to add a new column that is auto increment but NOT the primary key. Can this be done? I want this column so i can access the data with an id rather than a big long file path string.
ALTER TABLE `Media` ADD `ID` INT NOT NULL AUTO_INCREMENT
#1075 - Incorrect table definition; there can be only one auto column and it must be defined as a key

Change the table structure so the file path is declared to be unique instead of primary. Then add an auto-incrementing primary key.
ALTER TABLE `Media` DROP PRIMARY KEY,
ADD UNIQUE KEY (`FilePath`),
ADD `ID` INT AUTO_INCREMENT FIRST,
ADD PRIMARY KEY (`ID`);
There are advantages to having an integer primary key instead of a string. For instance, a secondary index will use the primary key to access the row, so having a full file path just makes the index larger than it needs to be.

ALTER TABLE
`Media`
ADD `ID` INT NOT NULL UNIQUE AUTO_INCREMENT

you must insert rows like this :
SET #ID = 0;
INSERT INTO Media (ID, SomeColumn) VALUES (#ID := #ID + 1, 'Some Text');

Related

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;

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.

Insert auto increment primary key to existing table

I am trying to alter a table which has no primary key nor auto_increment column. I know how to add an primary key column but I was wondering if it's possible to insert data into the primary key column automatically (I already have 500 rows in DB and want to give them id but I don't want to do it manually). Any thoughts? Thanks a lot.
An ALTER TABLE statement adding the PRIMARY KEY column works correctly in my testing:
ALTER TABLE tbl ADD id INT PRIMARY KEY AUTO_INCREMENT;
On a temporary table created for testing purposes, the above statement created the AUTO_INCREMENT id column and inserted auto-increment values for each existing row in the table, starting with 1.
suppose you don't have column for auto increment like id, no, then you can add using following query:
ALTER TABLE table_name ADD id int NOT NULL AUTO_INCREMENT primary key FIRST
If you've column, then alter to auto increment using following query:
ALTER TABLE table_name MODIFY column_name datatype(length) AUTO_INCREMENT PRIMARY KEY
For those like myself getting a Multiple primary key defined error try:
ALTER TABLE `myTable` ADD COLUMN `id` INT AUTO_INCREMENT UNIQUE FIRST NOT NULL;
On MySQL v5.5.31 this set the id column as the primary key for me and populated each row with an incrementing value.
In order to make the existing primary key as auto_increment, you may use:
ALTER TABLE table_name MODIFY id INT AUTO_INCREMENT;
Yes, something like this would do it, it might not be the best though. You might wanna make a backup:
$get_query = mysql_query("SELECT `any_field` FROM `your_table`");
$auto_increment_id = 1;
while($row = mysql_fetch_assoc($get_query))
{
$update_query = mysql_query("UPDATE `your_table` SET `auto_increment_id`=$auto_increment_id WHERE `any_field` = '".$row['any_field']."'");
$auto_increment_id++;
}
Notice that the the any_field you select must be the same when updating.
The easiest and quickest I find is this
ALTER TABLE mydb.mytable
ADD COLUMN mycolumnname INT NOT NULL AUTO_INCREMENT AFTER updated,
ADD UNIQUE INDEX mycolumnname_UNIQUE (mycolumname ASC);
I was able to adapt these instructions take a table with an existing non-increment primary key, and add an incrementing primary key to the table and create a new composite primary key with both the old and new keys as a composite primary key using the following code:
DROP TABLE IF EXISTS SAKAI_USER_ID_MAP;
CREATE TABLE SAKAI_USER_ID_MAP (
USER_ID VARCHAR (99) NOT NULL,
EID VARCHAR (255) NOT NULL,
PRIMARY KEY (USER_ID)
);
INSERT INTO SAKAI_USER_ID_MAP VALUES ('admin', 'admin');
INSERT INTO SAKAI_USER_ID_MAP VALUES ('postmaster', 'postmaster');
ALTER TABLE SAKAI_USER_ID_MAP
DROP PRIMARY KEY,
ADD _USER_ID INT AUTO_INCREMENT NOT NULL FIRST,
ADD PRIMARY KEY ( _USER_ID, USER_ID );
When this is done, the _USER_ID field exists and has all number values for the primary key exactly as you would expect. With the "DROP TABLE" at the top, you can run this over and over to experiment with variations.
What I have not been able to get working is the situation where there are incoming FOREIGN KEYs that already point at the USER_ID field. I get this message when I try to do a more complex example with an incoming foreign key from another table.
#1025 - Error on rename of './zap/#sql-da07_6d' to './zap/SAKAI_USER_ID_MAP' (errno: 150)
I am guessing that I need to tear down all foreign keys before doing the ALTER table and then rebuild them afterwards. But for now I wanted to share this solution to a more challenging version of the original question in case others ran into this situation.
Export your table, then empty your table, then add field as unique INT, then change it to AUTO_INCREMENT, then import your table again that you exported previously.
You can add a new Primary Key column to an existing table, which can have sequence numbers, using command:
ALTER TABLE mydb.mytable ADD pk_columnName INT IDENTITY
I was facing the same problem so what I did I dropped the field for the primary key then I recreated it and made sure that it is auto incremental . That worked for me . I hope it helps others
ALTER TABLE tableName MODIFY tableNameID MEDIUMINT NOT NULL AUTO_INCREMENT;
Here tableName is name of your table,
tableName is your column name which is primary has to be modified
MEDIUMINT is a data type of your existing primary key
AUTO_INCREMENT you have to add just auto_increment after not null
It will make that primary key auto_increment......
Hope this is helpful:)
Well, you have multiple ways to do this:
-if you don't have any data on your table, just drop it and create it again.
Dropping the existing field and creating it again like this
ALTER TABLE test DROP PRIMARY KEY, DROP test_id, ADD test_id int AUTO_INCREMENT NOT NULL FIRST, ADD PRIMARY KEY (test_id);
Or just modify it
ALTER TABLE test MODIFY test_id INT AUTO_INCREMENT NOT NULL, ADD PRIMARY KEY (test_id);
How to write PHP to ALTER the already existing field (name, in this example) to make it a primary key? W/o, of course, adding any additional 'id' fields to the table..
This a table currently created - Number of Records found: 4 name VARCHAR(20) YES
breed VARCHAR(30) YES
color VARCHAR(20) YES
weight SMALLINT(7) YES
This an end result sought (TABLE DESCRIPTION) -
Number of records found: 4
name VARCHAR(20) NO PRI
breed VARCHAR(30) YES
color VARCHAR(20) YES
weight SMALLINT(7) YES
Instead of getting this -
Number of Records found: 5
id int(11) NO PRI
name VARCHAR(20) YES
breed VARCHAR(30) YES
color VARCHAR(20) YES
weight SMALLINT(7) YES
after trying..
$query = "ALTER TABLE racehorses ADD id INT NOT NULL AUTO_INCREMENT FIRST, ADD PRIMARY KEY (id)";
how to get this? -
Number of records found: 4
name VARCHAR(20) NO PRI
breed VARCHAR(30) YES
color VARCHAR(20) YES
weight SMALLINT(7) YES
i.e. INSERT/ADD.. etc. the primary key INTO the first field record (w/o adding an additional 'id' field, as stated earlier.
No existing primary key
ALTER TABLE `db`.`table`
ADD COLUMN `id` INT NOT NULL AUTO_INCREMENT FIRST,
ADD PRIMARY KEY (`id`);
;
Table already has an existing primary key'd column
(it will not delete the old primary key column)
ALTER TABLE `db`.`table`
ADD COLUMN `id` INT NOT NULL AUTO_INCREMENT FIRST,
CHANGE COLUMN `prev_column` `prev_column` VARCHAR(2000) NULL ,
DROP PRIMARY KEY,
ADD PRIMARY KEY (`id`);
;
Note: column must be first for auto increment which is why the FIRST command.

MySQL populate new column with incrementing values without auto_increment

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

I need to auto_increment a field in MySQL that is not primary key

Right now, I have a table whose primary key is an auto_increment field. However, I need to set the primary key as username, date (to ensure that there cannot be a duplicate username with a date).
I need the auto_increment field, however, in order to make changes to row information (adding and deleting).
What is normally done with this situation?
Thanks!
Just set a unique index on composite of (username, date).
ALTER TABLE `table` ADD UNIQUE INDEX `name` (`username`, `date`);
Alternatively, you can try to
ALTER TABLE `table` DROP PRIMARY KEY, ADD PRIMARY KEY(`username`,`date`);
and I think in the latter case you need those columns to be declared NOT NULL.
I know this is old question, here is how i solved the problem -
ALTER TABLE `student_info` ADD `sn` INT(3) UNIQUE NOT NULL AUTO_INCREMENT FIRST
Use something like:
CREATE TABLE users (
id INT PRIMARY KEY AUTO_INCREMENT,
user VARCHAR(32) NOT NULL,
thedate DATE NOT NULL,
UNIQUE(user,thedate)
);
If you already have the table, and just want to add a unique constraint on
user+thedate, run
ALTER TABLE users ADD UNIQUE KEY user_date_idx (user, thedate);
Change your current primary key to be a unique key instead:
ALTER TABLE table DROP PRIMARY KEY, ADD UNIQUE KEY(username,date);
The auto_increment will function normally after that without any problems. You should also place a unique key on the auto_increment field as well, to use for your row handling:
ALTER TABLE table ADD UNIQUE KEY(id);