Using SQLyog, I was testing whether the correct value was set into table.
And I tried
SELECT type_service FROM service WHERE email='test#gmail.com'
So, only one result was output.
type_service
0
To continue to test, I tried to set value, 1 by force which gave the warning
Warning
There are 2 duplicates of the row you are trying to update. Do you
want to update all the duplicates?
Note: You can turn off this warning by unchecking Tools -> Preferences -> Others -> Prompt if multiple rows are getting updated.
But I thought I already placed limitations with where clause. So I pushed yes.
As a result, the value of all the data in type_service column was changed to 1.
Why?
You have 2 exact duplicate rows in table. Exact. It is a friendly warning, but most likely needs to be addressed by a slight schema change.
The most simple solution is to alter the table and add an auto_increment Primary Key column.
Mysql Alter Table Manual page here.
See this Webyog FAQ link.
Whenever I am about to spook up another table, I usually stub it out like:
create table blah
(
id int auto_increment primary key,
...
...
...
);
for safety sake.
Were you not to have the auto_increment PK, see the following.
create table people
(
firstName varchar(40) not null,
lastName varchar(40) not null,
age int not null
);
insert people (firstName,lastName,age) values ('Kim','Billings',30),('Kim','Billings',30),('Kim','Billings',30);
select * from people;
-- this could be bad:
update people
set age=40
where firstName='Kim' and lastName='Billings';
ALTER TABLE people ADD id INT PRIMARY KEY AUTO_INCREMENT;
select * from people; -- much nicer now, schema has an id column starting at 1
-- you now at least have a way to uniquely identify a row
Related
How do I set the initial value for an "id" column in a MySQL table that start from 1001?
I want to do an insert "INSERT INTO users (name, email) VALUES ('{$name}', '{$email}')";
Without specifying the initial value for the id column.
Use this:
ALTER TABLE users AUTO_INCREMENT=1001;
or if you haven't already added an id column, also add it
ALTER TABLE users ADD id INT UNSIGNED NOT NULL AUTO_INCREMENT,
ADD INDEX (id);
MySQL - Setup an auto-incrementing primary key that starts at 1001:
Step 1, create your table:
create table penguins(
my_id int(16) auto_increment,
skipper varchar(4000),
PRIMARY KEY (my_id)
)
Step 2, set the start number for auto increment primary key:
ALTER TABLE penguins AUTO_INCREMENT=1001;
Step 3, insert some rows:
insert into penguins (skipper) values("We need more power!");
insert into penguins (skipper) values("Time to fire up");
insert into penguins (skipper) values("kowalski's nuclear reactor.");
Step 4, interpret the output:
select * from penguins
prints:
'1001', 'We need more power!'
'1002', 'Time to fire up'
'1003', 'kowalski\'s nuclear reactor'
MySQL Workbench
If you want to avoid writing sql, you can also do it in MySQL Workbench by right clicking on the table, choose "Alter Table ..." in the menu.
When the table structure view opens, go to tab "Options" (on the lower bottom of the view), and set "Auto Increment" field to the value of the next autoincrement number.
Don't forget to hit "Apply" when you are done with all changes.
PhpMyAdmin:
If you are using phpMyAdmin, you can click on the table in the lefthand navigation, go to the tab "Operations" and under Table Options change the AUTO_INCREMENT value and click OK.
With CREATE TABLE statement
CREATE TABLE my_table (
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
name VARCHAR(100) NOT NULL,
PRIMARY KEY (id)
) AUTO_INCREMENT = 100;
or with ALTER TABLE statement
ALTER TABLE my_table AUTO_INCREMENT = 200;
First you need to add column for auto increment
alter table users add column id int(5) NOT NULL AUTO_INCREMENT FIRST
This query for add column at first.
Now you have to reset auto increment initial value. So use this query
alter table users AUTO_INCREMENT=1001
Now your table started with 1001
You could also set it in the create table statement.
`CREATE TABLE(...) AUTO_INCREMENT=1000`
Alternatively, If you are too lazy to write the SQL query. Then this solution is for you.
Open phpMyAdmin
Select desired Table
Click on Operations tab
Set your desired initial Value for AUTO_INCREMENT
Done..!
For this you have to set AUTO_INCREMENT value
ALTER TABLE tablename AUTO_INCREMENT = <INITIAL_VALUE>
Example
ALTER TABLE tablename AUTO_INCREMENT = 101
Also , in PHPMyAdmin , you can select table from left side(list of tables) then do this by going there.
Operations Tab->Table Options->AUTO_INCREMENT.
Now, Set your values and then press Go under the Table Options Box.
SET GLOBAL auto_increment_offset=1;
SET GLOBAL auto_increment_increment=5;
auto_increment_increment: interval between successive column values
auto_increment_offset: determines the starting point for the AUTO_INCREMENT column value.
The default value is 1.
read more here
I'm working on a game that requires the user (primarily kids) to combine a prefix and a suffix into a unique username, say, BlueBaron. Now there's only so many prefixes and suffixes, so if a user generates an existing one, a number is appended to it, say, BlueBaron2.
I have a table as follows:
| id | prefix_id | suffix_id | identifier_index | username | hashbrown | salt | coins | ranking | date_created | date_updated
The id is an auto-increment, unique, not-null primary key - I assume for this particular instance, I won't actually need to worry about the id. The prefix_id and suffix_id are not-null, but because they refer to common prefixes and suffixes, they are not unique. The rest of the rows are just not-nulls.
Ideally, I would like to check if a new user has the exact same prefix_id and suffix_id as another user, and increment the identifier_index.
I tried this with multiple (SELECT then INSERT) statements, but I fear the data might not be updated / unique (another user might have inserted between the time it took for you to insert, etc.).
Is this possible within a single insert statement? I've read of ON DUPLICATE KEY but I'm not sure that's applicable here.
UPDATE:
Per the comments and answers below, I've created a unique index for the three columns in question:
However, the identifier_index increments even when the prefix_id and suffix_id are different. And in the case of the last entry, wouldn't increment at all resulting in a duplicate entry error:
That's a good question. I'm no developer, but from a database admins view, I'd say that you need to do it like this.
You definitely need a unique index spanning over the 3 columns.
CREATE TABLE `a` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`prefix_id` varchar(10) NOT NULL,
`suffix_id` varchar(10) NOT NULL,
`identifier_index` int(11) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `uidx_psi` (`prefix_id`,`suffix_id`,`identifier_index`)
) ENGINE=InnoDB;
This is a must, you want to guarantee data integrity!
Your insert statement would look like this:
insert into a (prefix_id, suffix_id, identifier_index)
select 'asdf', 'qwer', coalesce(max(identifier_index) + 1, 1)
from a
where prefix_id = 'asdf' and suffix_id = 'qwer';
Be aware though, that you can run into deadlock issues. This happens when another transaction is trying to insert while this query is still running. Deadlocks are no serious issue, though. Typically an application is built in a way, that it simply tries again, until the insertion is successful.
i need autoincrement. for start like abc_1,abc_2. like this format? below shown code is for auto increment. but i need format like abc_ is constatanct then auto increment, format like abc_1,abc_2..
CODE
sql = "CREATE TABLE MY_TABLE
(
table_id int NOT NULL AUTO_INCREMENT,
PRIMARY KEY(table_id),
table_1 varchar(45),
table_2 varchar(45),
table_3 varchar(999),
table_4 varchar(45)
)"
You have 2 options - both include keeping the autoincrement field exactly as it is.
1st Option is to add a short char type field, which simply stores your Alpha part. When you want to retrieve the whole key, then you can SELECT (alpha_part + table_id) as ID. As you can see this generates smaller storage, but requires more work for each select statement.
2nd option is to add a longer column that gets populated by an insert trigger normally. It is simply storing the concatenation on creation and then you don't have to concatenate it when you want to select it. This option also allows you to create an index or clustered index easier.
CREATE TABLE MY_TABLE (
table_id int NOT NULL AUTO_INCREMENT, PRIMARY KEY(table_id),
alpha_part varchar(10) NOT NULL, -- This
display_id varchar(40) NOT NULL, -- OR This (not both)
table_1 varchar(45),
table_2 varchar(45),
table_3 varchar(999),
table_4 varchar(45) )
"Database Id" and "Insurance Policy Id" are two separate entities - they may contain the "same" number, but don't mix up what the database needs to perform effectively, with what your business application needs to generate IDs for customers. Business rules and database Id are separate entities. You can "seed" a policy Id from a database generated one, but if something changes the policy id (yes this happens) your database suddenly needs to be refactored and you don't want that to happen.
You could add another column to derive this value, then have a trigger that automatically updates this column to add the derived value whenever a row is inserted.
However, it is not clear why this would be needed. It is likely better to just store the number and derive the form abc_123 where that value needs to be used.
It was an interesting thing. so I googled custom auto increment structure and found some links. Most of the people are saying that its better to use trigger before insertion and I think it can be on possible solution for your problem. Look at the following link.
http://www.experts-exchange.com/Database/MySQL/Q_27602627.html
In my MySQL table I've created an ID column which I'm hoping to auto-increment in order for it to be the primary key.
I've created my table:
CREATE TABLE `test` (
`id` INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`name` VARCHAR( 50 ) NOT NULL ,
`date_modified` DATETIME NOT NULL ,
UNIQUE (
`name`
)
) TYPE = INNODB;
then Inserted my records:
INSERT INTO `test` ( `id` , `name` , `date_modified` )
VALUES (
NULL , 'TIM', '2011-11-16 12:36:30'
), (
NULL , 'FRED', '2011-11-16 12:36:30'
);
I'm expecting that my ID's for the above are 1 and 2 (respectively). And so far this is true.
However when I do something like this:
insert into test (name) values ('FRED')
on duplicate key update date_modified=now();
then insert a new record, I'm expecting it to be 3, however now I'm shown an ID of 4; skipping the place spot for 3.
Normally this wouldn't be an issue but I'm using millions of records which have thousands of updates every day.. and I don't really want to even have to think about running out of ID's simply because I'm skipping a ton of numbers..
Anyclue to why this is happening?
MySQL version: 5.1.44
Thank you
My guess is that the INSERT itself kicks off the code that generates the next ID number. When the duplicate key is detected, and ON DUPLICATE KEY UPDATE is executed, the ID number is abandoned. (No SQL dbms guarantees that automatic sequences will be without gaps, AFAIK.)
MySQL docs say
In general, you should try to avoid using an ON DUPLICATE KEY UPDATE
clause on tables with multiple unique indexes.
That page also says
If a table contains an AUTO_INCREMENT column and INSERT ... ON
DUPLICATE KEY UPDATE inserts or updates a row, the LAST_INSERT_ID()
function returns the AUTO_INCREMENT value.
which stops far short of describing the internal behavior I guessed at above.
Can't test here; will try later.
Is it possible to change your key to unsigned bigint - 18,446,744,073,709,551,615 is a lot of records - thus delaying the running out of ID's
Found this in mysql manual http://dev.mysql.com/doc/refman/5.1/en/example-auto-increment.html
Use a large enough integer data type for the AUTO_INCREMENT column to hold the
maximum sequence value you will need. When the column reaches the upper limit of
the data type, the next attempt to generate a sequence number fails. For example,
if you use TINYINT, the maximum permissible sequence number is 127.
For TINYINT UNSIGNED, the maximum is 255.
More reading here http://dev.mysql.com/doc/refman/5.6/en/information-functions.html#function_last-insert-id it could be inferred that the insert to a transactional table is a rollback so the manual says "LAST_INSERT_ID() is not restored to that before the transaction"
What about for a possible solution to use a table to generate the ID's and then insert into your main table as the PK using LAST_INSERT_ID();
From the manual:
Create a table to hold the sequence counter and initialize it:
mysql> CREATE TABLE sequence (id INT NOT NULL);
mysql> INSERT INTO sequence VALUES (0);
Use the table to generate sequence numbers like this:
mysql> UPDATE sequence SET id=LAST_INSERT_ID(id+1);
mysql> SELECT LAST_INSERT_ID();
The UPDATE statement increments the sequence counter and causes the next call to
LAST_INSERT_ID() to return the updated value. The SELECT statement retrieves that
value. The mysql_insert_id() C API function can also be used to get the value.
See Section 20.9.3.37, “mysql_insert_id()”.
It's really a bug how you can see here: http://bugs.mysql.com/bug.php?id=26316
But, apparently, they fixed it on 5.1.47 and it was declared as INNODB plugin problem.
A duplicate, but same problem, you can see here too: http://bugs.mysql.com/bug.php?id=53791 referenced to the first page mentioned here in this answer.
I have a table "Bestelling" with 4 columns: "Id" (PK), "KlantId", "Datum", "BestellingsTypeId", now I want to make the column Id auto_increment, however, when I try to do that, I get this error:
ERROR 1062: ALTER TABLE causes auto_increment resequencing, resulting in duplicate entry '1' for key 'PRIMARY'
SQL Statement:
ALTER TABLE `aafest`.`aafest_bestelling` CHANGE COLUMN `Id` `Id` INT(11) NOT NULL AUTO_INCREMENT
ERROR: Error when running failback script. Details follow.
ERROR 1046: No database selected
SQL Statement:
CREATE TABLE `aafest_bestelling` (
`Id` int(11) NOT NULL,
`KlantId` int(11) DEFAULT NULL,
`Datum` date DEFAULT NULL,
`BestellingstypeId` int(11) DEFAULT NULL,
PRIMARY KEY (`Id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
Anyone got an idea?
This will happen if the table contains an existing record with an id of 0 (or negative). Updating all existing records to use positive values will allow auto_increment to be set on that column.
Edit: Some people asked how that 0 got in there. For clarification, the MySQL Reference Manual states that "For numeric types, the default is 0, with the exception that for integer or floating-point types declared with the AUTO_INCREMENT attribute, the default is the next value in the sequence." So, if you performed an insert on a table without providing a value for the numeric column before the auto_increment was enabled, then the default 0 would be used during the insert. More details may be found at https://dev.mysql.com/doc/refman/5.0/en/data-type-defaults.html.
I also had this issue when trying to convert a column to auto_increment where one row had a value of 0. An alternative to changing the 0 value temporarily is via setting:
SET SESSION sql_mode='NO_AUTO_VALUE_ON_ZERO';
for the session.
This allowed the column to be altered to auto_increment with the zero id in place.
The zero isn't ideal - and I also wouldn't recommend it being used in an auto_increment column. Unfortunately it's part of an inherited data set so I'm stuck with it for now.
Best to clear the setting (and any others) afterwards with:
SET SESSION sql_mode='';
although it will be cleared when the current client session clsoes.
Full details on the 'NO_AUTO_VALUE_ON_ZERO' setting here.
This happens when MySQL can not determine a proper auto_increment value. In your case, MySQL choose 1 as next auto_increment value, however there is already row with that value in the table.
One way to resolve the issue is to choose a proper auto_increment value yourself:
ALTER TABLE ... CHANGE COLUMN `Id` `Id` INT(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT = 123456;
(Note the AUTO_INCREMENT=123456 at the end.)
The easiest way that I have found to solve this issue is to first set the table's AUTO INCREMENT value before altering the column. Just make sure that you set the auto increment value higher than the largest value currently in that column:
ALTER TABLE `aafest`.`aafest_bestelling`
AUTO_INCREMENT = 100,
CHANGE COLUMN `Id` `Id` INT(11) NOT NULL AUTO_INCREMENT
I tested this on MySQL 5.7 and it worked great for me.
Edit: Don't know exactly how that would be caused, but I do have a workaround.
First, create a new table like the old one:
CREATE TABLE aafest_bestelling_new LIKE aafest_bestelling;
Then change the column
ALTER TABLE `aafest`.`aafest_bestelling_new`
CHANGE COLUMN `Id` `Id` INT(11) NOT NULL AUTO_INCREMENT
Dump in the new data:
INSERT INTO aafest_bestelling_new
(KlantId, Datum, BestellingTypeId)
SELECT
KlantId, Datum, BestellingTypeId
FROM aafest_bestelling;
Move the tables:
RENAME TABLE
aafest_bestelling TO aafest_bestelling_old,
aafest_bestelling_new TO aafest_bestelling;
Maybe there's some corruption going on, and this would fix that as well.
P.S.: As a dutchman, I'd highly recommend coding in english ;)
I had a similar issue. Issue was the table had a record with ID = 0 similar to what SystemParadox pointed out. I handled my issue by the following steps:
Steps:
Update record id 0 to be x where x = MAX(id)+1
Alter table to set primary key and auto increment setting
Set seed value to be x+1
Change record id x back to 0
Code Example:
UPDATE foo SET id = 100 WHERE id = 0;
ALTER TABLE foo MODIFY COLUMN id INT(11) NOT NULL AUTO_INCREMENT;
ALTER TABLE foo AUTO_INCREMENT = 101;
UPDATE foo SET id = 0 WHERE id = 100;
This happens because your primary key column already has values.
As the error says ...
ALTER TABLE causes auto_increment resequencing, resulting in duplicate entry '1' for key 'PRIMARY'
which means that your column already has a primary key value 1 which when you auto_increment that column is reassigned causing duplication and hence this error
the solution to this is to remove the primary constraint and then empty the column. Then alter the table setting the primary key again, this time with auto increment.
This error comes because the any table contains an existing record with an id of 0 (or negative). Update all existing records to use positive values will allow auto_increment to be set on that column.
If this didn't work then export all the data and save it any where in you computer and dont first make foreign key relation then fill data in parent table .
This error will also happen if have a MyISAM table that has a composite AUTO_INCREMENT PRIMARY KEY and are trying to combine the keys
For example
CREATE TABLE test1 (
`id` int(11) NOT NULL,
`ver` int(10) unsigned NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`id`,`ver`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
INSERT INTO test1 (`id`, `ver`) VALUES (1,NULL),(1,NULL),(1,NULL), (2,NULL),(2,NULL),(2,NULL);
ALTER TABLE test1 DROP PRIMARY KEY, ADD PRIMARY KEY(`ver`);
Not being able to set an existing column to auto_increment also happens if the column you're trying to modify is included in a foreign key relation in another table (although it won't produce the error message referred to in the question).
(I'm adding this answer even though it doesn't relate to the specific error message in the body of the question because this is the first result that shows up on Google when searching for issues relating to not being able to set an existing MySQL column to auto_increment.)