Adding new field with Unique key index in existing MySQL table - mysql

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.

Related

How to add an UNIQUE field to existing table with data for my table using mySQL syntax

i`d like to add new unique field to my table but when i run command like
ALTER TABLE b_iblock_element ADD `XML_ID_UNIQUE` INT NOT NULL UNIQUE AFTER `XML_ID`
I have an error
Duplicate entry '0' for key 'XML_ID_UNIQUE'!
How can I ignore this error?
Maybe there`re another commands in mySQL?
If you have data in the table, you need to do this in three steps:
-- add the column, with no unique constraint
ALTER TABLE b_iblock_element
ADD `XML_ID_UNIQUE` INT NOT NULL AFTER `XML_ID`;
-- assign the values in the column some unique values
UPDATE b_iblock_element
SET XML_ID_UNIQUE = <something unique>;
-- add in the unique constraint
ALTER TABLE b_iblock_element ADD CONSTRAINT unq_XML_ID_UNIQUE UNIQUE (b_iblock_element);
<something unique> could be assigned as:
UPDATE b_iblock_element CROSS JOIN
(SELECT #rn := 0) params
SET XML_ID_UNIQUE = (#rn := #rn + 1);
But you might have some other way of assigning values.

How to alter the table that can accept not null values

Can you please tell How to alter the table so that it can accept the not null constraint
alter table customer add emp_id int not null foreign key references emp(emp_id)
I have tried as above, but it is showing error:
Msg 4901, Level 16, State 1, Line 1
ALTER TABLE only allows columns to be added that can contain nulls, or have a DEFAULT definition specified, or the column being added is an identity or timestamp column,
or alternatively if none of the previous conditions are satisfied the table must be
empty to allow addition of this column. Column 'emp_id1' cannot be added to non-empty table 'customer' because it does not satisfy these conditions.
The error is pretty clear.
You are trying to add a non-null column to a table that has data. When you add the column, it has no value. So, the default value is put into the table for the existing rows. There is no default value, so NULL is used.
You can solve this in a few ways. One would be to empty the table truncate table customer, add the new column, then load the data again.
Another way would be to add the column with NULL allowed. Then fill in the value everywhere and then add the NOT NULL constraint.

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.

MySQL: Creating new unique field in already populated table

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.

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
)