I am trying to insert an element in a table where there are already 3 rows.
Its a table called usuarios=[id (primary, autoincrement), fid, first_name, last_name....]
So there are already 3 rows with id's: 0,1,2
And when I am trying to execute this query (note I am not setting value for id attribute)
INSERT INTO usuarios (fid,email,pass,first_name,last_name,avatar,bday,fecha,id_loc,id_loc_from)
VALUES (-1,'toni#ideadeia.com','72253f579e7dc003da754dad4bd403a6','','','',NOW(),NOW(),'','')
I get this mysql error:
Duplicate entry '0' for key 1
extra: I don't know how this 3 items where inserted (if via interface, by console query, ..)
So question is, how can I make sure that the Primary Keyis autoincrement, and if not; how to set it? (will that solve the problem?)
You should be able to set it as auto-increment using this statement if you have rights to alter the table:
ALTER TABLE usuarios modify id INT(11) NOT NULL AUTO_INCREMENT;
Although I've seen reports of bugs that recommend instead dropping the colulmn and recreating it, if the above doesn't work for some reason. the syntax recommended in those posts is:
ALTER TABLE usuarios
DROP COLUMN id;
ALTER TABLE usuarios
ADD COLUMN idINT(11) NOT NULL AUTO_INCREMENT FIRST;
Warning: Do this in a test database first. You'd want to be careful doing this if the table is using this as a foreign key. It could fail at best, or break all the relationships at worst.
There's tons of info at the MySql reference manual.
Related
I have an old MS Access DB which I'm translating to a MySQL DB. I used bullzip to create the database but due to bad design the old MS Access database didn't have a unique primary key for most of the tables.
So I've created a id field but obviously it's empty for each entry, I wonder if there's a simple statement I can use to fill them up with 1, 2, 3, 4 etc...
EDIT:
I think I haven't gotten my question across properly. I know all about auto increment. Thats not the problem.
I have a table, full of records which I need kept and which came from a Access database that didn't have a unique id defined as a field. In otherwords I have fields for firstname, surname etc etc but no field 'id'. This seems absolutely crazy but apparently this database has been well used and never had any unique ids for any tables bar one. Weird!
Anyway, I've created a field in the table for id (and set it to auto increment of course) but obviously all the existing records don't have an id set currently. So I need to create one for each record.
Is there a way to fill all these records with unique numbers using a mysql statement?
Cheers
If you add an new id column to an existing table and make it AUTO_INCREMENT PRIMARY KEY, it will automatically populate it with incrementing values.
mysql> ALTER TABLE TheTable ADD COLUMN id INT AUTO_INCREMENT PRIMARY KEY;
mysql> SELECT id FROM TheTable;
-- outputs values 1, 2, 3, etc.
If you made an id column but didn't declare it AUTO_INCREMENT PRIMARY KEY, you can populate the column like this:
mysql> SET #id := 0;
mysql> UPDATE TheTable SET id = (#id := #id+1);
Use a predefined AUTO_INCREMENT field, and set the value as NULL when inserting new records, so that it automatically builds up an appropriate incrementer. Aside from that, there is no way (unless using a procedure) to create an incrementing set of values
Use the auto_increment feature of MySQL. MySQL will generate unique numbers for your id column.
For an explanation of the auto_increment feature see http://dev.mysql.com/doc/refman/5.0/en/example-auto-increment.html
If you just want a unique identifier, you can use the uuid() function. It takes up a bit more space than an integer, but it does what you want.
However, I agree with the other answers that you should add an auto increment column and repopulate the table. That is the simplest way to keep the ids unique over time, even as updates takes place, and using a more reasonable amount of storage.
I am not proficient in MySQL, but I have faced this same problem in other DBMS's and here is how I have addressed it when there was an AutoIncrement type facility, but the DBMS had no way to automatically apply it retroactively:
Rename the table you want to add the ID field to. So rename Table1 to Table1_Old.
Create a new Table1 that is a copy of Table1_Old except that it has no data in it.
Add your ID/AutoIncrement column to Table1
Now copy all of the data from Table1_Old to Table1, either skipping or specifying NULL for the ID column. (This is usually a single INSERT..SELECT.. command)
Drop Table1_Old.
The actual specifics and commands vary from DBMS to DBMS, but I have usually been able to find a way to do these steps.
Use AUTO_INCREMENT
CREATE TABLE insect
(
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
PRIMARY KEY (id),
name VARCHAR(30) NOT NULL,
date DATE NOT NULL,
origin VARCHAR(30) NOT NULL
);
Update
I believe, it seems tough task unless you won't create new table, I will suggest you to use this
SET #rank=0;
SELECT #rank:=#rank+1 AS rank, itemID FROM orders;
It will create a virtual column with the name rank for you, which have unique id value.
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.
I am using MySQL 5.1.56, MyISAM. My table looks like this:
CREATE TABLE IF NOT EXISTS `my_table` (
`number` int(11) NOT NULL,
`name` varchar(50) NOT NULL,
`money` int(11) NOT NULL,
PRIMARY KEY (`number`,`name`)
) ENGINE=MyISAM;
It contains these two rows:
INSERT INTO `my_table` (`number`, `name`, `money`) VALUES
(1, 'S. Name', 150), (2, 'Another Name', 284);
Now I am trying to insert another row:
INSERT INTO `my_table` (`number`, `name`, `money`) VALUES
(2, 'S. Name', 240);
And MySQL just won't insert it while telling me this:
#1062 - Duplicate entry '2-S. Name' for key 'PRIMARY'
I really don't understand it. The primary key is on the first two columns (both of them), so the row I am trying to insert HAS a unique primary key, doesn't it?
I tried to repair the table, I tried to optimize the table, all to no avail. Also please note that I cannot change from MyISAM to InnoDB.
Am I missing something or is this a bug of MySQL or MyISAM? Thanks.
To summarize and point out where I think is the problem (even though there shouldn't be):
Table has primary key on two columns. I am trying to insert a row with a new combination of values in these two columns, but value in column one is already in some row and value in column two is already in another row. But they are not anywhere combined, so I believe this is supposed to work and I am very confused to see that it doesn't.
Your code and schema are OK. You probably trying on previous version of table.
http://sqlfiddle.com/#!2/9dc64/1/0
Your table even has no UNIQUE, so that error is impossible on that table.
Backup data from that table, drop it and re-create.
Maybe you tried to run that CREATE TABLE IF NOT EXIST. It was not created, you have old version, but there was no error because of IF NOT EXIST.
You may run SQL like this to see current table structure:
DESCRIBE my_table;
Edit - added later:
Try to run this:
DROP TABLE `my_table`; --make backup - it deletes table
CREATE TABLE `my_table` (
`number` int(11) NOT NULL,
`name` varchar(50) NOT NULL,
`money` int(11) NOT NULL,
PRIMARY KEY (`number`,`name`),
UNIQUE (`number`, `name`) --added unique on 2 rows
) ENGINE=MyISAM;
I know this wasn't the problem in this case, but I had a similar issue of "Duplicate Entry" when creating a composite primary key:
ALTER TABLE table ADD PRIMARY KEY(fieldA,fieldB);
The error was something like:
#1062 Duplicate entry 'valueA-valueB' for key 'PRIMARY'
So I searched:
select * from table where fieldA='valueA' and fieldB='valueB'
And the output showed just 1 row, no duplicate!
After some time I found out that if you have NULL values in these field you receive these errors. In the end the error message was kind of misleading me.
I had a similar issue, but in my case it turned out that I used case insensitive collation - utf8_general_ci.
Thus, when I tried to insert two strings which were different in a case-sensitive comparison, but the same in the case-insensitive one, MySQL fired the error and I couldn't understand what a problem, because I used a case-sensitive search.
The solution is to change the collation of a table, e.g. I used utf8_bin which is case-sensitive (or utf8_general_cs should be appropriate one too).
In case this helps anyone besides the OP, I had a similar problem using InnoDB.
For me, what was really going on was a foreign key constraint failure. I was referencing a foreign key that did not exist.
In other words, the error was completely off. The primary key was fine, and inserting the foreign key first fixed the problem. No idea why MySQL got this wrong suddenly.
Less common cases, but keep in mind that according to DOC https://dev.mysql.com/doc/refman/5.6/en/innodb-online-ddl-limitations.html
When running an online ALTER TABLE operation, the thread that runs the ALTER TABLE operation will apply an “online log” of DML operations that were run concurrently on the same table from other connection threads. When the DML operations are applied, it is possible to encounter a duplicate key entry error (ERROR 1062 (23000): Duplicate entry), even if the duplicate entry is only temporary and would be reverted by a later entry in the “online log”. This is similar to the idea of a foreign key constraint check in InnoDB in which constraints must hold during a transaction.
In my case the error was caused by the outdated schema, one column was originally varchar(50) but the dump I was trying to import was created from a modified version of the schema that has varchar(70) for that column (and some of the entries of that field where using more than 50 chars).
During the import some keys were truncated and the truncated version was not unique anymore. Took a while to figure that out, I was like "but this supposedly duplicated key doesn't even exist!".
Try with auto increment:
CREATE TABLE IF NOT EXISTS `my_table` (
`number` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
`money` int(11) NOT NULL,
PRIMARY KEY (`number`,`name`)
) ENGINE=MyISAM;
Your code is work well on this demo:
http://sqlfiddle.com/#!8/87e10/1/0
I think you are doing second query (insert...) twice. Try
select * from my_table
before insert new row and you will get that your data already exist or not.
i have just tried, and if you have data and table recreation wouldnt work, just alter table to InnoDB and try again, it would fix the problem
In case anyone else finds this thread with my problem -- I was using an "integer" column type in MySQL. The row I was attempting to insert had a primary key with a value larger than allowed by integer. Switching to "bigint" fixed the problem.
As per your code your "number" and "Name" are primarykey and you are inserting S.NAME in both row so it will make a conflict. we are using primarykey for accessing complete data. here you cant access the data using the primarykey 'name'.
im a beginner and i think it might be the error.
In my case the error was very misleading. The problem was that PHPMyAdmin uses "ALTER TABLE" when you click on the "make unique" button instead of "ALTER IGNORE TABLE", so I had to do it manually, like in:
ALTER TABLE mytbl ADD UNIQUE (columnName);
This problem is often created when adding a column or using an existing column as a primary key. It is not created due to a primary key existing that was never actually created or due to damage to the table.
What the error actually denotes is that a pending key value is blank.
The solution is to populate the column with unique values and then try to create the primary key again. There can be no blank, null or duplicate values, or this misleading error will appear.
For me a noop on table has been enough (was already InnoDB):
ALTER TABLE $tbl ENGINE=InnoDB;
tl;dr: my view showed my table was empty but the view excluded existing rows.
I had the same problem but mine was because I was inserting the same test rows I had used before. When I checked to see if my table was empty, I used a view that excluded different tenants so the search came back empty. When I checked the actual table, the previous records were still there.
Once I had deleted the existing records, the insert worked. Only half a day of frustration lost to this one...
Had this error, when adding a composite primary key that is ADD PRIMARY KEY (column1, column2, ...) The value of all the columns in that row must not be duplicated.
For Example:
You do ADD PRIMARY KEY (name, country, number)
name
country
number
collin
Uk
5
collin
Uk
5
This will throw an error #1062 - Duplicate entry 'collin-UK-5' for key 'PRIMARY' because the columns combined have duplicate
So if you see this format of error just check and ensure that the columns you want to add a composite primary key to combined don't have duplicates.
Another reason you may be getting this error is because the same restriction exists in another related table, and they Keyname on the related table has the exact same name. I've had this happen once and it was quite difficult to identify.
i.e. if you have a trigger that inserts data to a different table (the "related" table) with the same restriction and same Keyname, MySQL will not include the name of the table throwing the error, only the Keyname.
As looking on your error #1062 - Duplicate entry '2-S. Name' for key 'PRIMARY' it is saying that you use primary key in your number field that's why it is showing duplicate Error on Number Field.
So Remove this primary Key then it inset duplicate also.
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.
I am using SQLite3. I load a table with say 30 rows using integer as Primary ID and it auto-increments.
Now I delete all the rows from the table and then, reload some new information onto the table.
Problem is: the row count (my PrimaryID) now starts with 31. Is there any way that I can start loading new rows from the number 1 onwards?
SQLite
Use:
DELETE FROM your_table;
DELETE FROM sqlite_sequence WHERE name = 'your_table';
Documentation
SQLite keeps track of the largest ROWID that a table has ever held using the special SQLITE_SEQUENCE table. The SQLITE_SEQUENCE table is created and initialized automatically whenever a normal table that contains an AUTOINCREMENT column is created. The content of the SQLITE_SEQUENCE table can be modified using ordinary UPDATE, INSERT, and DELETE statements. But making modifications to this table will likely perturb the AUTOINCREMENT key generation algorithm. Make sure you know what you are doing before you undertake such changes.
Found the answer on SO: SQLite Reset Primary Key Field
MySQL
Use:
ALTER TABLE tbl AUTO_INCREMENT = 1;
In either case, the database doesn't care if the id numbers are sequencial - only that the values are unique. If users never see the primary key value (they shouldn't, because the data can change & won't always be at that primary key value), I wouldn't bother with these options.
For MySQL:
Use TRUNCATE TABLE tablename to empty the table (delete all records) and reset auto increment count.
You can also use ALTER TABLE tablename AUTO_INCREMENT = 0; if you just want to reset the count.
For SQLite:
DELETE FROM tablename;
DELETE FROM SQLITE_SEQUENCE WHERE name='tablename';
References
SQLite AutoIncrement
MySQL AutoIncrement
For SQLite use (not need to delete and create the table)
UPDATE SQLITE_SEQUENCE SET SEQ=0 WHERE NAME='table_name';
For MySql use
ALTER TABLE table_name AUTO_INCREMENT = 1;
You should not use AUTOINCREMENT in this case. Simply define your primary key as INTEGER PRIMARY KEY and the count will be reset to 1 after a DELETE FROM query. Without AUTOINCREMENT, the default behaviour will still be an automatic increment of the primary key as long as you don't run out of space in your table (in that case, old - deleted - values will be reused).
More information available in the SQLite Autoincrement document.
ALTER TABLE tbl AUTO_INCREMENT = 0;