Mysql : How can i set number of gap 5 on each increment number in auto increment column? - mysql

I need to set each increment id +5 from the previous one generated id table wise. It means each auto-increment have to 5 number of the gap. Like this series 2,7,12,17 etc..
Any idea please share.

Please check the link:
https://dev.mysql.com/doc/refman/8.0/en/replication-options-master.html#sysvar_auto_increment_offset
SET ##auto_increment_offset=5;
SHOW VARIABLES LIKE 'auto_inc%';
CREATE TABLE autoinc2 (col INT NOT NULL AUTO_INCREMENT PRIMARY KEY);

You should not be demanding this requirement from an auto increment column. The contract of an auto increment column only guarantees that each generated value would be unique. The values would tend to generally be increasing, but if the counter were reset, and certain earlier records were deleted, there could be a value generated smaller than one which already exists. Instead, consider maintaining some sort of timestamp column which keeps track of when each record were added to your table. Then, using ROW_NUMBER, it is easy to generate the sequence you expect, e.g.
SELECT
5*ROW_NUMBER() OVER (ORDER BY ts_column) seq
FROM yourTable;
ORDER BY
ts_column;

If you need to increment by 5, you can set auto_increment_increment=5.
This will apply to all tables, so you should set it as a session variable, not a global variable. The session variable will only apply to INSERT statements made in your current session, not to other sessions.
Then change the option back to 1 before you INSERT to another table.
There is no feature in MySQL to make the auto_increment_increment option apply permanently and for all sessions, but only for a specific table.

Related

Does the MySQL Auto Increment Column Need to Be Unique or a Primary Key

I was developing a database in SQL Server where I was using an identity column as a seed for a primary key field. The intention was to reset the identity to 1 at the beginning of every year. This would allow us to create a PK of the Year - Identity Column.
Create Table Issues (
IssueID AS RIGHT(CONVERT(VARCHAR, Year(getdate()), 4),2) + '-' + RIGHT(REPLICATE('0', 2) +
CONVERT(VARCHAR, RecordID),3) NOT NULL PRIMARY KEY,
RecordID int Identity (1,1),.........)
The result would be
IssueID RecordID
20-001 1
20-002 2
20-003 3
21-001 1
etc....
Now I've been told we are going to use a MySQL database instead.
Can an Auto-Increment field in MySQL contain duplicate values like it can in SQL Server?
If Not, how can I do what I need to do in MySQL?
In MySQL, you can't use the default auto-increment feature for what you describe, a incrementing value that starts over per year.
This was a feature of the MyISAM storage engine years ago. An auto-increment that was the second column of a multi-column primary key would start counting from one for each distinct value in the first column of the PK. See the example under "MyISAM Notes" on this page: https://dev.mysql.com/doc/refman/8.0/en/example-auto-increment.html
But it's considered not a good idea to use MyISAM because it does not support ACID. In general, I would find another way of solving this task. I would not use MyISAM.
In InnoDB, there's no way the table will generate a value that is a duplicate of a value currently in the table, or even a value less than the maximum value previously generated for that table. In other words, there's no way to "fill in the gaps" using auto-increment.
You can use ALTER TABLE mytable AUTO_INCREMENT=1 to reset the counter, but the value you set it will automatically advance to the max value currently in the table + 1.
So you'll have to generate it using either another table, or else something other than the MySQL database. For example, I've seen some people use memcached, which supports an atomic "increment and return counter" operation.
Another thing to consider: If you need a row counter per year, this is actually different from using MySQL's auto-increment feature. It's not easy to use the latter as a row counter. Besides, what happens if you roll back a transaction or delete a row? You'd end up with non-consecutive RecordId values, with unexplained "gaps." It's also a fact about the auto-increment feature that it guarantees that subsequent id's will be greater, but it does not guarantee to generate all values consecutively. So you'll get gaps eventually anyway.
In MySQL a table can have only one auto_increment column and this column must be a part of the primary key. See details here.
Technical workaround for your task would be creating of a table with a single auto_increment column, and you can obtain auto_increment value by inserting a record into this table and immediately calling standard MySQL function last_inser_id(). When time comes you should truncate the table - in this case the auto_increment count will be reset.

Auto_increment temporary gaps in MySQL?

Let's say I have a table defined by:
CREATE TABLE People (
id SERIAL,
name TEXT
);
If I first find the maximum id in the table and then run the following query:
SELECT (id, name)
FROM People
WHERE id <= [maximum id found before];
I'll get a list of people. If I run the same query again with the same maximum id:
Am I guaranteed to get the same results?
Or is it possible that the first query returned a list with gaps which were filled in before the second query was executed, causing the second query to have more rows?
Assume that no changes are made to the database except sequential insert operations from any number of concurrent connections.
EDIT:
I'll try to clarify the specific case I'm concerned about. Let's say MySQL gets five transactions at around the same time. Transactions A and B both insert a person into People. Transaction C finds the maximum id. Transactions D and E both perform the query written above.
Is it possible for this sequence of events:
A is assigned an id
B is assigned the next id
B is committed
C is committed and returns the id of B
D is committed and returns a list that does not include the row inserted by A
A is committed
E is committed and returns a list that does include the row inserted by A
EDIT:
I'm thinking this scenario is impossible due to atomicity, but I'm hoping for confirmation from someone who understands ACID a little better than I do.
I think you are guaranteed to get the same list, gaps should never be filed in unless you're manually inserting them somehow. (although, if there are gaps i assume rows can be deleted, so it may not be exactly the same list because more may have been deleted.)
from How to reset AUTO_INCREMENT in MySQL?
You can reset the counter with:
ALTER TABLE tablename AUTO_INCREMENT = 1 For InnoDB you cannot set the
auto_increment value lower or equal to the highest current index.
(quote from ViralPatel):
Note that you cannot reset the counter to a value less than or equal
to any that have already been used. For MyISAM, if the value is less
than or equal to the maximum value currently in the AUTO_INCREMENT
column, the value is reset to the current maximum plus one. For
InnoDB, if the value is less than the current maximum value in the
column, no error occurs and the current sequence value is not changed.
See How to Reset an MySQL AutoIncrement using a MAX value from another
table? on how to dynamically get an acceptable value.

SQL MyISAM, reset auto increment for new inserts only

So we have a really big database table that holds important data for a limited amount of time.
The problem is that the table is never truncated completely, and the auto-increment id value is reaching 9 digits, which somehow needs to be reset in the near future.
We really need to reset it without truncating the current data, and rows currently in the table need to keep the same id value.
So f.ex the record with id '12345679' needs to keep id '123456789' in the database, but after a reset the next new insert should get id '1' and then '2' and so on. It will not be any collision between these new low values and the old values, but i don't know how to reset the auto increment value in this way.
That's not possible:
You cannot reset the counter to a value less than or equal to any that
have already been used. For MyISAM, if the value is less than or equal
to the maximum value currently in the AUTO_INCREMENT column, the value
is reset to the current maximum plus one. For InnoDB, if the value is
less than the current maximum value in the column, no error occurs and
the current sequence value is not changed.
(Source: https://dev.mysql.com/doc/refman/5.5/en/alter-table.html
What you can do is create a new table and insert new data into it. Then create a VIEW that will return a UNION of these two tables.
For example, let's say your current table is called myData:
rename myData to myData_Original
create a new table name myData_New (with the same structure)
create a VIEW named myData
myData view:
CREATE VIEW myData
AS
SELECT *
FROM myData_New
UNION ALL
SELECT *
FROM myData_Original
;

Auto Increment Problem in Mysql

I created a table and set a field to auto increment some thing like this:
CREATE TABLE t1(id BIGINT NOT NULL PRIMARY KEY AUTO_INCREMENT) ENGINE = MyISAM AUTO_INCREMENT = 123456;
But to some reason i deleted some of the rows in the table.
Now the question is when i insert new rows in the table the new rows should be assigned id's of the rows which have been deleted rather than assigning new id's.
I do not want to reset all the id's
How can i do this??
Help appreciated:)
Sorry to say, but that is not the use of AUTO_INCREMENT. If you want to re-use id's, then you would have to write your own trigger functions, and doing this is generally considered bad practice.
Imagine you were on id 50,000, and deleted an entry with id 1... would you really want the next record you add to re-use id 1?
The whole point of AUTO_INCREMENT is to auto increment...
You can explicitly assign these ids though and mysql will allow it.
You are going to have to do this manually rather than rely on MySQL to do it for you. The AUTO-INCREMENT flag keeps an integer that is incremented upon every insert statement and is assigned as the PK of the subsequent insert. Unless you want to write an update trigger that resets this value to the lowest non-used integer, I would suggest processing this in a server-side scripting language.
In any case, though, why is using the auto increment value a problem?
To reset the autoincrement value, you can use
ALTER TABLE t1 AUTO_INCREMENT=1
The next inserted record will use ID 1.
This might be something you're after.
alter table Users AUTO_INCREMENT=0;
This will reset the auto_increment back to 0 + whatever the current highest id is.
if you have 30, your next entry would be 31

Reset MySQL auto_increment when a large number already exists?

I have a table with an auto incrementing column. I need to set one of the rows to 1000 and never touch it again, but now that I've set it to 1000, auto increment keeps starting at 1001 and refuses to start at 1. Is there any way to get around this?
You cannot:
To change the value of the
AUTO_INCREMENT counter to be used for
new rows, do this:
ALTER TABLE t2 AUTO_INCREMENT = value;
You cannot reset the counter to a
value less than or equal to any that
have already been used. For MyISAM, if
the value is less than or equal to the
maximum value currently in the
AUTO_INCREMENT column, the value is
reset to the current maximum plus one.
For InnoDB, if the value is less than
the current maximum value in the
column, no error occurs and the
current sequence value is not changed.
http://dev.mysql.com/doc/refman/5.1/en/alter-table.html
Simple and short answer: you can't do this.
If you could, what would happen if you start your auto-increment at 1 and insert 1000 rows? The last couldn't be inserted due to "duplicate key"-error.
If you have to have a predefinded entry, with an id that never changes and is easy to remember, why don't you use 0 for that? Or, if you really need to use 1000, what's the problem with letting the other columns start at 1001?
Assuming you have no other row ID with 1000, you can insert the row to the bottom of the table, then you can simply use the update command:
UPDATE table.column SET id = 1000 WHERE id = current_id;
Assuming id is your auto-increment column. And current_id should be replaced with the id that the row is inserted at.
You can use MS Access that link to MySQL as external table, and you can change the auto increment table field value from MS Access via copy paste from Excel (first, you need to arrange the value of auto increment in Excel).
You could use the following statements:
UPDATE tbl SET id=1000 WHERE id=current_id;
ALTER TABLE tbl AUTO_INCREMENT=1001;