I have a table like this:
// colors
+----+-------+
| id | color |
+----+-------+
| 1 | red |
| 2 | blue |
+----+-------+
-- id column is auto increment (PK)
When I insert some new values into that table, sometimes there is some gaps in the id
column. Something like this:
INSERT INTO colors (color)
SELECT 'gray'
UNION ALL
SELECT 'black'
UNION ALL
SELECT 'green'
UNION ALL
SELECT 'pink';
/* output:
+----+-------+
| id | color |
+----+-------+
| 1 | red |
| 2 | blue |
| 6 | gray | -- expected id is 3, but it is 6
| 7 | black |
| 8 | green |
| 9 | pink |
+----+-------+
*/
A repro of this on SQL Fiddle and RexTester
Well what's wrong? Why sometimes the value of id
goes out of the normal order? How can I prevent it?
EDIT: I've created the table like this:
CREATE TABLE colors (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
color VARCHAR(30) NOT NULL
)
When I paste this query twice in two different steps:
INSERT INTO colors (color)
SELECT 'gray'
UNION ALL
SELECT 'black'
UNION ALL
SELECT 'green'
UNION ALL
SELECT 'pink';
And here is the result:
As you see the order of id
column isn't continuous. Why?
Note1: Engine is InnoDB.
Note2: Here is the number of auto increment for next row: