MySQL: Creating new unique field in already populated table - mysql

I need to create a field in a database table, already populated with data. Of course just adding the field empty is not possible. I can only think of creating a new table with a new structure and copy the existing data to the new table, but I wonder if there is a n easier way.
Hint: it is a composite key, comprised of 3 other fields in the same table.
Edit: the field holds a varchar value
Edit: since some of you ask, it is not possible to create a new UNIQUE field in a populated table just by using ADD UNIQUE. It duplicates the new (empty or not) value throughout all entries. Example:
ALTER TABLE 'tablename' ADD 'fieldname' VARCHAR( 64 ) NOT NULL ,
ADD UNIQUE (
'fieldname'
)
error: Duplicate entry '' for key 'fieldname'

Of course just adding the field empty is not possible.
Why?
I'd do the following:
Create field by ALTER TABLE t ADD COLUMN new_column *type_definition*
Update newly created field like UPDATE t SET new_column=*computation_expression*
Add index by ALTER TABLE t ADD INDEX ... (or ALTER TABLE t ADD PRIMARY KEY ... if you need it to be primary).

Hint: it is a composite key, comprised of 3 other fields in the same table.
This sounds like a red-flag to me. You want to create a new field with a unique constraint comprised of the values of 3 other fields that already exist in the same table?
If all you want to do is to enforce that the combination of those three fields is unique, then you should just add a unique constraint on those 3 existing fields (not a new field with duplicate data).
ALTER TABLE tablename ADD UNIQUE (fieldname1, fieldname2, fieldname3);

You can create a new field with AUTO_INCREMENT option:
ALTER TABLE `your_table` ADD COLUMN `new_id` INT NOT NULL AUTO_INCREMENT

This is a possible workaround:
alter table foo add bar varchar(36) not null default '';
then add a trigger as per default value of GUID in for a column in mysql

I came accross the same problem that I had to add a unique constraint on an already populated table.
The error:
Integrity constraint violation: 1062 Duplicate entry '' for key 'url_UNIQUE'
How did I solve it? I put the id of the row into the unique field to avoid duplicates:
UPDATE content SET new_url = content_id WHERE new_url = '';
I then didn't have any duplicate rows anymore and was able to add the unique constraint.

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

Adding new field with Unique key index in existing MySQL table

I am trying to add a column with Unique Key (so it will not have duplicate records) in existing MySQL table that contains multiple rows of data.
ALTER TABLE `common`.`fraud_payment_log`
ADD `retainer_id` VARCHAR( 20 ) NOT NULL,
ADD `http_referrer` VARCHAR( 255 ) NULL ,
ADD UNIQUE (`retainer_id`);
But it is throwing below error:
ERROR 1062 (23000): Duplicate entry '' for key 'retainer_id'
The error is because of the duplicate empty value which will come when we adding a new column in the existing table with records.
Can anyone please suggest how to achieve this?
You cannot add a unique, non-NULL column to a table that has more than one row. By definition, two rows would get the same value.
Add the columns first, allowing NULL values:
ALTER TABLE `common`.`fraud_payment_log`
ADD `retainer_id` VARCHAR( 20 ) NULL,
ADD `http_referrer` VARCHAR( 255 ) NULL;
Now, populate the column so it has different values. Say:
update `common`.`fraud_payment_log` cross join
(select #rn := 0) vars
set retainer_id = (#rn := #rn + 1);
Then add the unique constraint. I usually do this with the index directly:
create unique index idx_fpl_retainer on `common`.`fraud_payment_log`(retainer_id);
If the table is empty, then just recreate the table with all the columns you want.
Follow this steps:
Add new field which is not unique
Update table and put unique values in that field
Alter table to make this field as unique
You should first add the column, then populate it with the unique values, then add the UNIQUE constraint.
You should specify a DEFAULT NULL; NULL doesn't count against UNIQUE checks, so your table will be first filled with NULL values, then you'll proceed to fill it as you wish.
Create new column using UI or query(My new column is sensorID)
Fire this :
UPDATE client set sensorID=id
In above query client is my table , sensorID is my newly added column on which I wanted to apply unique, id is my primary key type column in existing table.

How add unique key to existing table (with non uniques rows)

I want to add complex unique key to existing table. Key contains from 4 fields (user_id, game_id, date, time).
But table have non unique rows.
I understand that I can remove all duplicate dates and after that add complex key.
Maybe exist another solution without searching all duplicate data. (like add unique ignore etc).
UPD
I searched, how can remove duplicate mysql rows - i think it's good solution.
Remove duplicates using only a MySQL query?
You can do as yAnTar advised
ALTER TABLE TABLE_NAME ADD Id INT AUTO_INCREMENT PRIMARY KEY
OR
You can add a constraint
ALTER TABLE TABLE_NAME ADD CONSTRAINT constr_ID UNIQUE (user_id, game_id, date, time)
But I think to not lose your existing data, you can add an indentity column and then make a composite key.
The proper syntax would be - ALTER TABLE Table_Name ADD UNIQUE (column_name)
Example
ALTER TABLE 0_value_addition_setup ADD UNIQUE (`value_code`)
I had to solve a similar problem. I inherited a large source table from MS Access with nearly 15000 records that did not have a primary key, which I had to normalize and make CakePHP compatible. One convention of CakePHP is that every table has a the primary key, that it is first column and that it is called 'id'. The following simple statement did the trick for me under MySQL 5.5:
ALTER TABLE `database_name`.`table_name`
ADD COLUMN `id` INT NOT NULL AUTO_INCREMENT FIRST,
ADD PRIMARY KEY (`id`);
This added a new column 'id' of type integer in front of the existing data ("FIRST" keyword). The AUTO_INCREMENT keyword increments the ids starting with 1. Now every dataset has a unique numerical id. (Without the AUTO_INCREMENT statement all rows are populated with id = 0).
Set Multiple Unique key into table
ALTER TABLE table_name
ADD CONSTRAINT UC_table_name UNIQUE (field1,field2);
I am providing my solution with the assumption on your business logic. Basically in my design I will allow the table to store only one record for a user-game combination. So I will add a composite key to the table.
PRIMARY KEY (`user_id`,`game_id`)
Either create an auto-increment id or a UNIQUE id and add it to the natural key you are talking about with the 4 fields. this will make every row in the table unique...
For MySQL:
ALTER TABLE MyTable ADD MyId INT AUTO_INCREMENT PRIMARY KEY;
If yourColumnName has some values doesn't unique, and now you wanna add an unique index for it. Try this:
CREATE UNIQUE INDEX [IDX_Name] ON yourTableName (yourColumnName) WHERE [id]>1963 --1963 is max(id)-1
Now, try to insert some values are exists for test.

Is it possible to add new unique index to the existing database table?

I have database table but without the index, and I want to add index id to that table, that will be uniqe for each row, how can I do this using mysql?
Assuming you don't have a key on the table already you can do this:
ALTER TABLE whatever ADD id Int NOT NULL AUTO_INCREMENT PRIMARY KEY;
And remember you can add FIRST to the end of that line to make it the first column which would be a good idea for an id.

How to restrict Blank values in Primary Key column

I have a database of sql server 2008 which I am using to display in a gridview. I have written some code to add new rows in asp.net and C# as Code behind.
When ever a row is added through the Programming I have put some checking which will not allow the required values to be Null.
But, here comes my problem when ever any one of the user adds a new row manually by opening the Database, then a blank value is allowing in the Primary key column which is not 'Null value'.
So, here I have to restrict even not to allow blank values in primary key column, how can I solve this problem.
You need a check constraint
ALTER TABLE [TableName]
ADD CONSTRAINT [CK_PrimaryKeyNotEmpty]
CHECK
(
LEN([ColumnName]) > 0
)
I'm having trouble figuring out what you actual question is.
1) If you need to make a column not accept null values:
Add a constraint to the column in the db:
ALTER TABLE [Table] ALTER COLUMN [Column] INTEGER NOT NULL
See: Altering a column: null to not null
2) If you need to restrict your PK column to only certain values add a constraint:
ALTER TABLE Table
ADD CONSTRAINT CK_Table_Column_Range CHECK (
Column >= 0
)