How does MySQL Auto Increment work? - mysql

I was just creating a new table using MySQL Query Browser, and noticed there's a tick under Auto Increment Column. How does that work?
When adding to the database programatically, do I just add a number, and then the database automatically increments that number?
Everytime a NEW user registers on my site, I want their Customer ID (integer only) to auto increment, so I don't have to try and randomly generate a unique number.
Can this be done simply?
Thank you!

When adding to the database programatically, do I just add a number, and then the database automatically increments that number?
Yes, that's the way auto_increment works.
The value will be incremented for each new row
The value is unique, duplicates are not possible
If a row is deleted, the auto_increment column of that row will not be re-assigned.
The auto_increment value of the last inserted row can be accessed using the mySQL function LAST_INSERT_ID() but it must be called right after the insert query, in the same database connection
mySQL Reference

1 more,
You can insert your own value also (ie your random value).

Yes. Auto_Increment columns work like they say on the tin. Tips
when INSERT - ing, use NULL or omit the column
Use LAST_INSERT_ID() (or API equivalents) to obtain the last generated value.
for security and business logic reasons, it's usually better form to not directly use a key value for a customer identifier. Consider using Hashed / randomised surrogate customer keys instead.
Ta

Yes, that's the exact purpose of AUTO_INCREMENT. It looks at whatever is the current increment value for that table, and stores that value plus 1 for the new row that comes in, automatically. You can omit that field from your INSERT statements and MySQL will handle it for you for every new row that comes in, giving each row its own unique ID.

When you enable Auto Increment an ID will always get automatically added whenever a new record is made.. Example:
If you have 1 record with ID 1 in your table and you add a new record, the ID will automatically be 2.

Related

Can Autoincrement field ever use the same value twice?

I have a table1 with an id field, type AutoIncrement. I need to copy the entire record from table1 into table2 if there is no record with the same id in table2. Then I delete the record from table1.
I need to know that if table1 gets new records, the id field will never be a number that was ever used before. Does this happen automatically, or do I need to do something to ensure this?
I tried deleting some records and adding new ones, and it really didn't use the same id, but I'm not sure that this is what always happens.
It is possible to duplicate numbers in autoincremet field quite easy, but normally applications don't work this way.
Access remembers last inserted value in autoincrement field and uses it for calculating next value. You cannot insert particular value into autoincrement field using table designer or recordset in VBA, but it's possible if you use INSERT SQL statement. So, if autoincrement field has no unique index, you can insert any value. Also if you insert value less than maximum existing number, Access will generate duplicates automatically.
So I would not recommend rely on unique autoincrement numbers without unique index.
INSERT SQL can be used for resetting numeration without dropping field/table, just run query like this in query builder or using VBA:
INSERT INTO Table1 ( id ) SELECT 1;
This is table with autoincrement field ID I just created:
it is really so, Auto-increment fields in MS Access are always incremental, even if records are deleted, database compacted, etc.
The proposed number can be reset deleting the auto-increment field, perform the copy of the table and then adding the auto-increment field again.
Auto increment never uses the same # even though it's deleted from the table.
It requires complete reset so that it will start from the base and create new #.

Text and Autoincremented number together in a field in mysql

I want to create a table, where the fields are labeled with an auto-incremented number at the end, such as:
Comp1
Comp2
Comp3
Is that possible? then if yes, how?
I have a question for you first. Will the word "Comp" ever change?
If it will never change just create a column called id that's auto increment and prefix it as "Comp" in your code.
If the word "Comp" may change you have the option to split into two column. One id and another prefix. You will be querying with the id and prefix in your where clause.
Select * from yourtable where id=2232 and prefix ="Comp";
Another option is what you exactly desire, create a column of type binary(16) and use the hex() and unhex() functions to store and retrieve the id. However you will still need to maintain a separate column for auto incrementing ID. If you don't want to do that then before you insert get the last inserted record and then increment it yourself then insert. But this may have the chance for collision. Be sure to index this field you plan to query it. Get a buy in from your DBAs as they won't be happy as your index will grow larger :)

How to control auto increment id?

I have an entity with a strategy to auto generate an id based on an integer column in MySQL. Things work, but while testing exceptions and related rollbacks, I noticed that MySQL does not reset last incremented value.
So a successful save produces entity id 1
An attempted save gets entity id 2 but is rolled back.
Then a successful save of a new entity gets entity id 3.
Consequently, in the table we have two records. One with id 1 and the other with id 3.
Are there any ways to control this? Basically, in the scenario I have just described, I would like to see two entities: one with id set to 1 and the other with id set to 2.
No, you can't change that. That is how it is supposed to be.
An auto-increment id has to be unique. That's all.
Auto-increment numbers have to be unique, but they don't have to be consecutive. They are monotonically increasing only as a coincidence of their implementation.
You can always insert a specific value and bypass the auto-increment mechanism. But you'd have to know what value is the "next" value. To avoid race conditions, you'd have to lock the table, query the MAX(id)+1 and then insert that value.
And that's exactly what MySQL would have to do, too, if it were to do this automatically.
The way auto-increment works now allows maximum concurrency without race conditions. So it is by design that it "loses" some values from time to time, when you rollback an INSERT, or else if you subsequently DELETE a value.
You can handle it using your own auto increment logic.
Have a Max+1 idgenerator or have a table that maintains PK auto generated IDs of such tables.
A table like this
LastKey TableName
1 TableX
5 TableY
Everytime, you will have to query from this table to get the incremented id.

Get last created ID with auto-increment in MySQL

I have a primary index on column URL but at the same time I need to have records with URL left blank which won't be permitted by the index.
I thought of a solution which is to add a new column called ID and make it auto-increment.
So I need to get the ID created with auto-increment on INSERT so that I stick it to column URL too. How can I do this?
If you can think of a better solution please tell
thanks
It is almost certainly better to use the mysql wrapper in your scripting language of choice to acquire the last insert id, but you can SELECT LAST_INSERT_ID(); to get it with mysql itself.
The solution may depend on what other columns you have on your table. It will be hard for you to add an auto_increment column to a table that already has data. The process will be to create a new table with the new column added and add the data from the old table and then drop the old table and re-name the new one to the matching name.

MySQL, autoincrement sequence?

In a MySQL database column that has been set to AUTO_INCREMENT, can I assume that the values will always be created sequentially?
For instance, if 10 rows are inserted and receive values 1,2,3,...10, and then 3 is deleted, can I assume the next row inserted will receive 11?
The reason I ask is that I'd like to sort values based on the order in which they were inserted into the table, and if I can sort based on the auto incremented primary key it will be a little easier.
From what I understand from the manual; yes. Each table has it's own 'next auto increment value' that is incremented by the amount defined in auto_increment_increment (http://dev.mysql.com/doc/refman/5.0/en/replication-options-master.html#sysvar_auto_increment_increment) and that is never automatically reset, even though it can be manually reset. But as #miku said, if possible a timestamp would be preferable.
I've seen auto_increment mainly used for the primary key column. If you want to sort items by say date_added you should create an extra timestamp, date/datetime or int (epoch) column.
This way you make your intent explicit and easier to follow - also you can safely migrate, export and import your DB without the need to worry about how auto_increment is handled.