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

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.

Related

Can we make existing column as primary key?

I have one column name Token and I'm generating random numbers and saving them in token but sometimes it saves duplicate tokens so I want to make it unique.
I want to know will it affect existing records.
If you try to add a unique constraint (or primary key constraint) to a column that contains non-unique values, the alter statement will just fail. You need to first update the column so all values are unique (or remove duplicates), and then alter the table.
ALTER table Student add primary key (studentID)
Use the Alter command to edit table's DDL and then add a primary key to it by specifying the column.
If the primary key already exist, then first you will have to drop it before defining another PK by -
ALTER table STUDENT drop CONSTRAINT <constraint_name>
Try doing this
ALTER table_namePersons ADD UNIQUE (Token);
After doing this if you'll try to insert a duplicate key you will have an error and catching it you can generate another token

Pairing Unique Columns MySQL?

I'd like to know how to make paired columns unique key?
I'm working on MySQL workbench, and right now I've set two columns (follow,following) to be UQ, I'm assuming this is Unique Key?
So when I tried to insert rows, I tried to insert
follow following
3 5
3 6
But follow is unique key. But i'd like to only do unique key for a pair only, not individual numbers.
Thanks
If i'm not mistaken you have only set a unique key for each column. Maybe you want compound column to be UNIQUE, try
ALTER TABLE tableName ADD CONSTRAINT tb_UQ UNIQUE (follow, following)
if you run the ALTER statement, the example data above is valid but if you try to insert another pair of 3, 5, it is guaranteed to fail.
If you created the table with follow as the PRIMARY key, then the RDBMS will enforce uniqueness based on that column alone.
As an alternate to JW's suggestion, you can change the PRIMARY KEY:
ALTER TABLE tableName DROP PRIMARY KEY;
ALTER TABLE tableName ADD CONSTRAINT tb_UQ PRIMARY KEY (follow, following);

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.

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.

Add another primary key to table in mysql

I want to add another primary key to a table in mysql.
I use phpmyadmin to communicate with mysql server.
When I click the primary icon for the desired field it gives me this error:
#1075 - Incorrect table definition; there can be only one auto column and it must be defined as a key
Edited:
here's the query:
ALTER TABLE `files` DROP PRIMARY KEY ,ADD PRIMARY KEY ( `file_type` )
How can I do it?
As the name "primary" key says, there may be only one of that (ref: Highlander).
What you might want to try is a UNIQUE KEY, that acts just like a primary for most purpouses. Auto_increment doesn't seem to fulfill any purpouse if used a second time - what'ts the point of two fields carrying exactly the same information?
I believe in your case, what you need is a composite key. I do not know your table structure, but here is a general example taken from here,
CREATE TABLE track(
album CHAR(10),
disk INTEGER,
posn INTEGER,
song VARCHAR(255),
PRIMARY KEY (album, disk, posn)
)
In this case, there is a combination of 3 columns which avoid the duplicate records as you require. Please let me know if I have any mistakes in understanding your scenario.
The error message says it, I think:
the auto_increment column must be key.
So use this query first:
ALTER TABLE 'files' CHANGE 'id' 'id' INT( 10 ) UNSIGNED NOT NULL;
this will remove the auto_increment.
Also, I recommend the Uniqe key as suggested by other answer. I believe there should always (almost) be an Id column in each table.
We can Give Primary Key only once for a table. You can prefer UNIQUE KEY to prevent duplicate records
ALTER TABLE Persons
ADD UNIQUE (P_Id)
You can mark all the fields you want as primary keys, including the existing one. The system internally will drop the existing one and will set all you marked.