MySQL Auto increment primary key increases by 10 - mysql

On azure I created a new MySQL Database instance. In this db I create a table using this script:
CREATE TABLE ROLES(
ID INTEGER PRIMARY KEY AUTO_INCREMENT,
ROLE_NAME VARCHAR(30) NOT NULL
);
Then I insert values using this script:
INSERT INTO `beezzy`.`roles` (`ROLE_NAME`) VALUES ('admin');
INSERT INTO `beezzy`.`roles` (`ROLE_NAME`) VALUES ('owner');
INSERT INTO `beezzy`.`roles` (`ROLE_NAME`) VALUES ('consultant');
after execution table contains such rows:
Why DB generates IDs like '11' and '21'?
I run the same script on my local machine and everything works fine. IDs was '1', '2', '3'

Please run the following query.
SELECT ##auto_increment_increment
If the value is more than 1 then set it to 1 by the following query:
SET ##auto_increment_increment=1;
Note: This change is visible for the current connection only.
EDIT:
In order to set it globally so that other connections can also see the change you need to set it for global and session too.
SET ##GLOBAL.auto_increment_increment = 1;
SET ##SESSION.auto_increment_increment = 1;
So other connections can see this change now.
More:
This value will be reset if you restart your MySQL server. In order to make this change permanent you need to write this variable under [mysqld] secion in your my.cnf [for linux] or my.ini [for windows] file.
[mysqld]
auto-increment-increment = 1

Your autoincrement is probably 10, however this is probably by design. Azure uses ClearDB which uses an autoincrement of 10 with a reason: namely replication.
When I use auto_increment keys (or sequences) in my database, they
increment by 10 with varying offsets. Why?
ClearDB uses circular replication to provide master-master MySQL
support. As such, certain things such as auto_increment keys (or
sequences) must be configured in order for one master not to use the
same key as the other, in all cases. We do this by configuring MySQL
to skip certain keys, and by enforcing MySQL to use a specific offset
for each key used. The reason why we use a value of 10 instead of 2 is
for future development.
You should not change the autoincrement value.
cleardb faq

Related

My heroku backend data is being created with ID that skip every 10 [duplicate]

On azure I created a new MySQL Database instance. In this db I create a table using this script:
CREATE TABLE ROLES(
ID INTEGER PRIMARY KEY AUTO_INCREMENT,
ROLE_NAME VARCHAR(30) NOT NULL
);
Then I insert values using this script:
INSERT INTO `beezzy`.`roles` (`ROLE_NAME`) VALUES ('admin');
INSERT INTO `beezzy`.`roles` (`ROLE_NAME`) VALUES ('owner');
INSERT INTO `beezzy`.`roles` (`ROLE_NAME`) VALUES ('consultant');
after execution table contains such rows:
Why DB generates IDs like '11' and '21'?
I run the same script on my local machine and everything works fine. IDs was '1', '2', '3'
Please run the following query.
SELECT ##auto_increment_increment
If the value is more than 1 then set it to 1 by the following query:
SET ##auto_increment_increment=1;
Note: This change is visible for the current connection only.
EDIT:
In order to set it globally so that other connections can also see the change you need to set it for global and session too.
SET ##GLOBAL.auto_increment_increment = 1;
SET ##SESSION.auto_increment_increment = 1;
So other connections can see this change now.
More:
This value will be reset if you restart your MySQL server. In order to make this change permanent you need to write this variable under [mysqld] secion in your my.cnf [for linux] or my.ini [for windows] file.
[mysqld]
auto-increment-increment = 1
Your autoincrement is probably 10, however this is probably by design. Azure uses ClearDB which uses an autoincrement of 10 with a reason: namely replication.
When I use auto_increment keys (or sequences) in my database, they
increment by 10 with varying offsets. Why?
ClearDB uses circular replication to provide master-master MySQL
support. As such, certain things such as auto_increment keys (or
sequences) must be configured in order for one master not to use the
same key as the other, in all cases. We do this by configuring MySQL
to skip certain keys, and by enforcing MySQL to use a specific offset
for each key used. The reason why we use a value of 10 instead of 2 is
for future development.
You should not change the autoincrement value.
cleardb faq

Getting id generated in a trigger for further requests

I have a table with two columns:
caseId, referring to a foreign table column
caseEventId, int, unique for a given caseId, which I want to auto-increment for the same caseId.
I know that the auto-increment option based on another column is not available in mySql with InnoDb:
MySQL Auto Increment Based on Foreign Key
MySQL second auto increment field based on foreign key
So I generate caseEventId into a trigger. My table:
CREATE TABLE IF NOT EXISTS mydb.caseEvent (
`caseId` CHAR(20) NOT NULL,
`caseEventId` INT NOT NULL DEFAULT 0,
PRIMARY KEY (`caseId`, `caseEventId`),
# Foreign key definition, not important here.
ENGINE = InnoDB;
And my trigger:
CREATE DEFINER=`root`#`%` TRIGGER `mydb`.`caseEvent_BEFORE_INSERT` BEFORE INSERT ON `caseEvent` FOR EACH ROW
BEGIN
SELECT COALESCE((SELECT MAX(caseEventId) + 1 FROM caseEvent WHERE caseId = NEW.caseId),0)
INTO #newCaseEventId;
SET NEW.`caseEventId` = #newCaseEventId;
END
With this, I get my caseEventId which auto-increments.
However I need to re-use this new caseEventId in further calls within my INSERT transaction, so I place this id into #newCaseEventId within the trigger, and use it in following instructions:
START TRANSACTION;
INSERT INTO mydb.caseEvent (caseId) VALUES ('fziNw6muQ20VGYwYPW1b');
SELECT #newCaseEventId;
# Do stuff based on #newCaseEventId
COMMIT;
This seems to work just fine but... what about concurrency, using connection pools etc...?
Is this #newCaseEventId variable going to be shared with all clients using the same connection, can I run into problems when my client server launches two concurrent transactions? This is using mysql under nodejs.
Is this safe, or is there a safer way to go about this? Thanks.
Edit 2020/09/24
FYI I have dropped this approach altogether. I was trying to use the db in a way it isn't meant to be used.
Basically I have dropped caseEventId, and any index which is supposed to increment nicely based on a given column value.
I rely instead on properly written queries on the read side, when I retrieve data, to recreate my caseEventId field...
That is no problem, the user defined variables a per client.
That means every user has its own use defined varoables
User-defined variables are session specific. A user variable defined by one client cannot be seen or used by other clients. (Exception: A user with access to the Performance Schema user_variables_by_thread table can see all user variables for all sessions.) All variables for a given client session are automatically freed when that client exits.
see manul

Solution for auto increment reset in mysql

While implementing mysql in my project it is found that if we restart mysql service AUTO_INCREMENT of that table is reset to value less than the current maximum value in the primary key column.
According to this, suppose one of table having ID (As primary key) up to 100 records and if DELETE is performed on 100th ID and restarted mysql service and performed INSERT then it will again add new row with ID 100. INSERT without restart of mysql service will add 101 ID.(like 1,2,3,4...99,101).
How to avoid this? Means after next restart it must start with 101; Is it possible so?

Reset Auto_Increment on MySql via MSSQL? I'll even settle for Truncate

I have a MSSQL Server 2008 R2 system that updates various tables on various systems during a nightly process. I have a MySQL linked server that has an Auto_Increment on one of it's tables. This tables contents are deleted and replaced each night. This of course does not reset the increment. I have tried:
ALTER TABLE REMOTEMYSQL...[TableWithAI] AUTO_INCREMENT = 1
And I get:
Incorrect syntax near 'AUTO_INCREMENT'
I can successfully:
delete from REMOTEMYSQL...[TableWithAI]
But obviously that doesn't reset the increment on the MySQL side
I tried:
Truncate TABLE REMOTEMYSQL...[TableWithAI]
and I get:
Cannot find the object "TableWithAI" because it does not exist or you do not have permissions.
But the MySql user that is used in the link has full permissions. How can I ether delete the contents and zero the increment, or zero the increment by itself?
Assuming you have your MySQL already configured as a linked server, you can fire off non-query statements to linked servers with EXEC:
EXEC('ALTER TABLE TableWithAI AUTO_INCREMENT = 1') AT LinkedMySQLServerName;
I believe the query should be in MySQL syntax, but I'm not in a position to test from where I'm at.

timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP can be null on one machine but not another?

I have a MySql table with a field defined as:
`created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
On my local machine, I can run:
INSERT INTO mytbl (id, user_id, created) VALUES(88882341234, 765, null);
SELECT id, user_id, created FROM mytbl WHERE id = '88882341234';
And then 'created' will show something like '2014-06-13 21:16:42'.
But on my staging server, if I run the same queries, I get this error:
Column 'created' cannot be null.
The schemas of the tables are the same (across local and staging), which I ensured via mysqldump (to clone the table before running this test).
I'm running MySql 5.6.17 on both machines. I've also ensured that both have the same sql_mode.
What could be the problem?
P.S. For people who don't know why I'd be setting a non-nullable field's value to null, MySql Docs say:
In addition, you can initialize or update any TIMESTAMP column to the
current date and time by assigning it a NULL value, unless it has been
defined with the NULL attribute to permit NULL values.
I found what the problem was. The MySql variable/parameter explicit_defaults_for_timestamp was OFF on my local machine but ON on my remote machine.
I visited my AWS RDS Parameter Groups page and changed explicit_defaults_for_timestamp from 1 to 0.
Then I went to my AWS RDS instances page to watch when "Parameter Group" changed from "Applying" to "pending-reboot".
Then I rebooted the particular instance.
These links helped me:
https://stackoverflow.com/a/23392448/470749
How to import MySQL binlog that contains INSERTs of a TIMESTAMP field with default value CURRENT_TIMESTAMP
https://forums.aws.amazon.com/thread.jspa?threadID=132676
The main problem is that the INSERT is just wrong: it's trying to insert a NULL into a non-nullable column.
What you should do is simply fix the query:
INSERT INTO mytbl (id, user_id) VALUES(88882341234, 765);
The reason this causes an error only on the staging server is that the server operates in strict SQL mode and therefore immediately aborts when you try to insert an incorrect value into created.
You can easily check the SQL mode in effect with SELECT ##SESSION.sql_mode and change it (perhaps so you can reproduce the error on your own server) with
SET SESSION sql_mode = 'STRICT_ALL_TABLES'