The AUTO_INCREMENT column attribute in MySQL – A beginning perspective.

AUTO_INCREMENT. Without a care in the world, we reach for this attribute in MySQL. Quicker than any snake, we slap it to the PRIMARY KEY column in a CREATE TABLE command. Or ‘tic’ the check box in phpMyAdmin and carry on like nobody else’s business. What does AUTO_INCREMENT do? What is it used for? Is its value always the next incremental number? Can we capture, manipulate, and use it to do our bidding? Those are all great questions I would like to know myself. Let’s find out…


sweeping-view-of-numbered-chairs

Photo by Paul Bergmeir on Unsplash


OS and DB used:

  • Xubuntu Linux 16.04.5 LTS (Xenial Xerus)
  • MySQL 5.7.23

One of the most common uses (I am aware of) for the AUTO_INCREMENT attribute, is to create a unique identifier for a record in a table. Therefore, we typically use it as a tables’ PRIMARY KEY. Honestly, to this point in my SQL learning/development career, that is all I have ever used it for.

Let’s create a simple table and perform some ‘rudimentary’ INSERT‘s on it and get a feel for the AUTO_INCREMENT attribute.

1
2
3
mysql> CREATE TABLE demo(id INTEGER AUTO_INCREMENT PRIMARY KEY,
     > name VARCHAR(25));
Query OK, 0 rows affected (0.29 sec)

With that taken care of, I’ll INSERT some values but make note in the difference between a single INSERT and multiple INSERT‘s.
I’ll issue, a single INSERT with the below statement:

1
2
3
4
5
6
7
8
9
10
mysql> INSERT INTO demo(name) VALUES('Apples');
Query OK, 1 row affected (0.02 sec)

mysql> SELECT * FROM demo;
+----+--------+
| id | name   |
+----+--------+
|  1 | Apples |
+----+--------+
1 row in set (0.00 sec)

Query results via the SELECT statement, reflect the id column value is 1.
By not supplying a value for the id column, MySQL automatically assigned it 1. (AUTO_INCREMENT starts at 1.)
Prior to continuing with a multiple VALUES INSERT, I’ll make mention of a handy function you can use with AUTO_INCREMENT. LAST_INSERT_ID(). I’ll include the documentation’s exact wording here for a concise rundown.

With no argument, LAST_INSERT_ID() returns a BIGINT UNSIGNED (64-bit) value representing the first automatically generated value successfully inserted for an AUTO_INCREMENT column as a result of the most recently executed INSERT statement. The value of LAST_INSERT_ID() remains unchanged if no rows are successfully inserted.

Let’s see how LAST_INSERT_ID() works:

1
2
3
4
5
6
7
mysql> SELECT LAST_INSERT_ID();
+------------------+
| LAST_INSERT_ID() |
+------------------+
|                1 |
+------------------+
1 row in set (0.00 sec)

That’s makes sense. Only one INSERT statement has been issued so far.

I’ll cover a multiple VALUES INSERT with this next statement:

1
2
3
4
mysql> INSERT INTO demo(name)
     > VALUES('Mark'),('Ham-n-cheese'),('57 Chevy');
Query OK, 3 rows affected (0.05 sec)
Records: 3  Duplicates: 0  Warnings: 0

So, the LAST_INSERT_ID() value is 4 right? I just inserted 3 more records, which should put the id column value at 4.

1
2
3
4
5
6
7
mysql> SELECT LAST_INSERT_ID();
+------------------+
| LAST_INSERT_ID() |
+------------------+
|                2 |
+------------------+
1 row in set (0.00 sec)

Hmm… Interesting.
And unexpected.
Reasoning, although 3 rows were indeed inserted, the id value automatically assigned to the first of them (‘Mark’) is 2.
And that is the value returned in this call to LAST_INSERT_ID().

Let’s try something. I have a .sql source file with these SQL statements:

1
2
3
4
5
6
7
8
9
BEGIN;

INSERT INTO demo(name)
VALUES('Little River');

INSERT INTO demo(name)
VALUES('Happy Time');

COMMIT;

I’ll source that file in the terminal, (not shown) then check the LAST_INSERT_ID() after querying all records:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
mysql> SELECT * FROM demo;
+----+--------------+
| id | name         |
+----+--------------+
|  1 | Apples       |
|  2 | Mark         |
|  3 | Ham-n-cheese |
|  4 | 57 Chevy     |
|  5 | Little River |
|  6 | Happy Time   |
+----+--------------+
6 rows in set (0.00 sec)

mysql> SELECT LAST_INSERT_ID();
+------------------+
| LAST_INSERT_ID() |
+------------------+
|                6 |
+------------------+
1 row in set (0.00 sec)

Let’s try it again, but this time I’ll code in an error so we can see how the AUTO_INCREMENT attribute handles it. Here’s the error INSERT:

1
2
3
4
5
6
7
8
9
BEGIN;

INSERT INTO demo(name)
VALUES('B-52''s');

INSERT INTO dema(name)
VALUES('Happy Days');

COMMIT;

After running that source file we get:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
mysql> SELECT * FROM demo;
+----+--------------+
| id | name         |
+----+--------------+
|  1 | Apples       |
|  2 | Mark         |
|  3 | Ham-n-cheese |
|  4 | 57 Chevy     |
|  5 | Little River |
|  6 | Happy Time   |
|  7 | B-52's       |
+----+--------------+
7 rows in set (0.00 sec)

mysql> SELECT LAST_INSERT_ID();
+------------------+
| LAST_INSERT_ID() |
+------------------+
|                7 |
+------------------+
1 row in set (0.00 sec)

The first INSERT completed no problem but the next statement failed. That id would have been 8. Again, LAST_INSERT_ID() has no trouble keeping up with the current value.

If you want to explicitly list out the table column names in your INSERT statement, you can be sure the next automatically generated value will be inserted for the AUTO_INCREMENT column.
There are 2 options available you can provide the VALUES list for an AUTO_INCREMENT column.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
mysql> INSERT INTO demo(id, name)
    -> VALUES (0, 'Peanut Butter');
Query OK, 1 row affected (0.04 sec)

mysql> SELECT * FROM demo;
+----+---------------+
| id | name          |
+----+---------------+
|  1 | Apples        |
|  2 | Mark          |
|  3 | Ham-n-cheese  |
|  4 | 57 Chevy      |
|  5 | Little River  |
|  6 | Happy Time    |
|  7 | B-52's        |
|  8 | Peanut Butter |
+----+---------------+
8 rows in set (0.00 sec)

By inserting 0, the next available value for the id column is automatically generated and available.
(Note: If the NO_AUTO_VALUE_ON_ZERO SQL mode is enabled, this will not work.)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
mysql> INSERT INTO demo(id, name)
    -> VALUES(NULL, 'Moon Dance');
Query OK, 1 row affected (0.04 sec)

mysql> SELECT * FROM demo;
+----+---------------+
| id | name          |
+----+---------------+
|  1 | Apples        |
|  2 | Mark          |
|  3 | Ham-n-cheese  |
|  4 | 57 Chevy      |
|  5 | Little River  |
|  6 | Happy Time    |
|  7 | B-52's        |
|  8 | Peanut Butter |
|  9 | Moon Dance    |
+----+---------------+
9 rows in set (0.00 sec)

In this example, specifying NULL in place of the value for the listed id column furnishes the next available value (9 in this example) to be inserted.
I’ll refer to the MySQL CREATE TABLE documentation for a precise explanation.

“An integer or floating-point column can have the additional attribute AUTO_INCREMENT. When you insert a value of NULL (recommended) or 0 into an indexed AUTO_INCREMENT column, the column is set to the next sequence value. Typically this is value+1, where value is the largest value for the column currently in the table. AUTO_INCREMENT sequences begin with 1.”

What if you want full control of the value for the AUTO_INCREMENT column? Can you have your cake and eat it too?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
mysql> INSERT INTO demo(id, name)
    -> VALUES (15, 'Demo Table');
Query OK, 1 row affected (0.03 sec)

mysql> SELECT * FROM demo;
+----+---------------+
| id | name          |
+----+---------------+
|  1 | Apples        |
|  2 | Mark          |
|  3 | Ham-n-cheese  |
|  4 | 57 Chevy      |
|  5 | Little River  |
|  6 | Happy Time    |
|  7 | B-52's        |
|  8 | Peanut Butter |
|  9 | Moon Dance    |
| 15 | Demo Table    |
+----+---------------+
10 rows in set (0.00 sec)

Okay, we see that it’s possible to explicitly supply the desired value.
But, does AUTO_INCREMENT continue to the next available value from the custom value specified? Or from the previous INSERT?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
mysql> INSERT INTO demo(name)
    -> VALUES ('Max Ammount');
Query OK, 1 row affected (0.02 sec)

mysql> SELECT * FROM demo;
+----+---------------+
| id | name          |
+----+---------------+
|  1 | Apples        |
|  2 | Mark          |
|  3 | Ham-n-cheese  |
|  4 | 57 Chevy      |
|  5 | Little River  |
|  6 | Happy Time    |
|  7 | B-52's        |
|  8 | Peanut Butter |
|  9 | Moon Dance    |
| 15 | Demo Table    |
| 16 | Max Ammount   |
+----+---------------+
11 rows in set (0.00 sec)

The query results above reflect the value increments from the explicitly set value.

Recommended reading and resources:

My plan with this blog post is to highlight and demonstrate basic usage of AUTO_INCREMENT. In a follow-up blog post, I will look deeper into the LAST_INSERT_ID() function. It provides a fantastic use in certain situations in MySQL TRIGGER and Stored Procedures. Please leave any corrections, comments, and suggestions in the comments below. As always, thanks for reading!

Explore the official MySQL 5.7 Online Manual for more information.

A Call To Action!

Thank you for taking the time to read this post. I truly hope you discovered something interesting and enlightening. Please share your findings here, with someone else you know who would get the same value out of it as well.

Visit the Portfolio-Projects page to see blog post/technical writing I have completed for clients.

Have I mentioned how much I love a cup of coffee?!?!

To receive email notifications (Never Spam) from this blog (“Digital Owl’s Prose”) for the latest blog posts as they are published, please subscribe (of your own volition) by clicking the ‘Click To Subscribe!’ button in the sidebar on the homepage! (Feel free at any time to review the Digital Owl’s Prose Privacy Policy Page for any questions you may have about: email updates, opt-in, opt-out, contact forms, etc…)

Be sure and visit the “Best Of” page for a collection of my best blog posts.


Josh Otwell has a passion to study and grow as a SQL Developer and blogger. Other favorite activities find him with his nose buried in a good book, article, or the Linux command line. Among those, he shares a love of tabletop RPG games, reading fantasy novels, and spending time with his wife and two daughters.


Disclaimer: The examples presented in this post are hypothetical ideas of how to achieve similar types of results. They are not the utmost best solution(s). The majority, if not all, of the examples provided, are performed on a personal development/learning workstation-environment and should not be considered production quality or ready. Your particular goals and needs may vary. Use those practices that best benefit your needs and goals. Opinions are my own.

Advertisements

Hey thanks for commenting! Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.