Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL: can an AUTO_INCREMENT generate values out of order?

Assume I've got the table:

CREATE TABLE test (
    ID INT AUTO_INCREMENT PRIMARY KEY,
    InsertTime DATETIME
) ENGINE = InnoDB;

And, through an Apache/PHP website, as a response to web requests, I keep doing this:

INSERT INTO test (InsertTime) values (NOW());

Is it safe to assume that if row1.ID > row2.ID then row1.InsertTime >= row2.InsertTime? Or perhaps through some unfortunate combination of factors (multi-CPU server in a replicated environment with the moons of Jupiter in the correct alignment etc.) this can fail?

Note: I don't have any issues. I'm writing a new piece of software and am wondering if I can rely on sorting by ID to also sort by dates (only NOW() will even be inserted into that column).

like image 957
Vilx- Avatar asked Dec 25 '11 14:12

Vilx-


People also ask

How does the AUTO_INCREMENT work in MySQL?

Auto-increment allows a unique number to be generated automatically whenever a new record is inserted into a table. This feature is especially useful in the primary key field so that the key can be set automatically every time a new record is inserted.

Is auto increment unique?

Auto-increment allows a unique number to be generated automatically when a new record is inserted into a table. Often this is the primary key field that we would like to be created automatically every time a new record is inserted.

Is primary key auto increment by default?

No. A primary key must be unique and that has to be 100% guaranteed, and NON NULL A primary key should be stable if ever possible and not change.

Can we change auto increment value in MySQL?

In MySQL, the syntax to change the starting value for an AUTO_INCREMENT column using the ALTER TABLE statement is: ALTER TABLE table_name AUTO_INCREMENT = start_value; table_name. The name of the table whose AUTO_INCREMENT value you wish to change.


Video Answer


2 Answers

I think most problems will come from the call to NOW() instead of the AUTO_INCREMENT. I suspect most computers at some point print NOW() dates out of order! This is usually either because a sysadmin changed the clock, or because NTP changed the clock.

like image 156
Julius Musseau Avatar answered Sep 21 '22 20:09

Julius Musseau


I think you will have some inconsistency once a year because of DST (surely, it depends on server settings). Other than that I don't see why it may fail.

like image 32
a1ex07 Avatar answered Sep 17 '22 20:09

a1ex07