MariaDB AUTO_INCREMENT: generate IDs and read the inserted value

In MariaDB, AUTO_INCREMENT is a column attribute that automatically assigns an integer ID to a new row. A common setup is an integer primary key omitted from the INSERT column list. Read the generated value from the inserting connection with LAST_INSERT_ID(). Deletions and rollbacks can leave gaps.

Create an auto-increment column

A table can have only one AUTO_INCREMENT column, and it must be part of a key. InnoDB requires it to be the first column of that index when the key is composite. Use PRIMARY KEY or UNIQUE if you need the ID itself to be unique. An exhausted integer type does not grow automatically. MariaDB Docs · AUTO_INCREMENT

Use a practice database named learning with CREATE, INSERT, SELECT, DELETE, and ALTER permissions. If any exercise table already exists, choose a fresh practice database. The expected results assume a standalone InnoDB instance, a fresh connection with autocommit, and increment and offset settings both equal to 1.

USE learning;
SELECT @@session.auto_increment_increment AS increment_step,
       @@session.auto_increment_offset AS increment_offset;
CREATE TABLE auto_id_demo (
    id INT UNSIGNED NOT NULL AUTO_INCREMENT,
    name VARCHAR(40) NOT NULL,
    PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
SHOW CREATE TABLE auto_id_demo;

Read generated IDs in the same connection

INSERT INTO auto_id_demo (name) VALUES ('item_a');
SELECT LAST_INSERT_ID() AS new_id;

INSERT INTO auto_id_demo (name) VALUES ('item_b'), ('item_c');
SELECT LAST_INSERT_ID() AS first_id_of_batch;

SELECT id, name FROM auto_id_demo ORDER BY id;

The first insert returns 1 as new_id. One statement then inserts two rows, with first_id_of_batch equal to 2 and actual IDs 1, 2, and 3. LAST_INSERT_ID() returns the first automatically generated value for that statement. An insert on a different connection does not change the result in this connection. In an application, read the generated key from the driver or keep the same physical connection through the read. MAX(id) can also see concurrent writes and cannot reliably identify your insert. MariaDB Docs · LAST_INSERT_ID()

Compare explicit values and SQL modes

INSERT INTO auto_id_demo (id, name) VALUES (100, 'explicit_id');
INSERT INTO auto_id_demo (name) VALUES ('generated_id');
SELECT LAST_INSERT_ID() AS generated_id;
SELECT id, name FROM auto_id_demo ORDER BY id;

Inserting 100 explicitly makes the next automatic value greater than 100. Here it is 101. A smaller unused ID does not move the counter backward, and a duplicate primary key causes an error. Omitting the column or inserting NULL or DEFAULT also requests an automatic value.

CREATE TABLE auto_zero_demo (
    id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY
) ENGINE=InnoDB;
SET @previous_sql_mode = @@SESSION.sql_mode;

SET SESSION sql_mode = '';
INSERT INTO auto_zero_demo (id) VALUES (0);
SELECT LAST_INSERT_ID() AS generated_from_zero;

SET SESSION sql_mode = 'NO_AUTO_VALUE_ON_ZERO';
INSERT INTO auto_zero_demo (id) VALUES (0);
SELECT id FROM auto_zero_demo ORDER BY id;

SET SESSION sql_mode = @previous_sql_mode;

In the next example, try inserting zero twice into a separate table with one connection. With NO_AUTO_VALUE_ON_ZERO disabled, MariaDB generates 1. With it enabled, MariaDB stores 0. The sorted result is 0, 1. The last statement restores the original session mode. Omitting the ID avoids mode-dependent behavior in an application. MariaDB Docs · NO_AUTO_VALUE_ON_ZERO

Understand gaps after deletion and rollback

DELETE FROM auto_id_demo WHERE id = 2;
START TRANSACTION;
INSERT INTO auto_id_demo (name) VALUES ('rollback_item');
SELECT LAST_INSERT_ID() AS rolled_back_id;
ROLLBACK;
INSERT INTO auto_id_demo (name) VALUES ('after_rollback');
SELECT LAST_INSERT_ID() AS next_id;
SELECT id, name FROM auto_id_demo ORDER BY id;

ID 2 remains absent after deletion. The insert in the transaction reserves 102, and ROLLBACK removes the row. The next insert returns 103, leaving IDs 1, 3, 100, 101, and 103. Failed or canceled inserts can also reserve values. MAX(id) does not measure row count, and a gap alone is not evidence of lost data. Strictly consecutive business numbers need separate allocation rules. MariaDB Docs · InnoDB AUTO_INCREMENT

Change the next value and reset an empty table

ALTER TABLE auto_id_demo AUTO_INCREMENT = 1000;
INSERT INTO auto_id_demo (name) VALUES ('raised_start');
SELECT LAST_INSERT_ID() AS raised_id;

ALTER TABLE auto_id_demo AUTO_INCREMENT = 1;
INSERT INTO auto_id_demo (name) VALUES ('after_lower_request');
SELECT LAST_INSERT_ID() AS actual_id;

Use ALTER TABLE to raise the next automatic value while retaining existing IDs. In the example, the next row receives 1000. With ID 1000 still present, requesting a start at 1 makes the next row receive 1001. MariaDB Docs · AUTO_INCREMENT FAQ

CREATE TABLE auto_reset_demo (
    id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(40) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 AUTO_INCREMENT=50;
INSERT INTO auto_reset_demo (name) VALUES ('initial_row');
SELECT id FROM auto_reset_demo;
DELETE FROM auto_reset_demo;
ALTER TABLE auto_reset_demo AUTO_INCREMENT = 1;
INSERT INTO auto_reset_demo (name) VALUES ('restarted_row');
SELECT id FROM auto_reset_demo;

The separate auto_reset_demo table starts at 50. After deleting its rows, setting its counter to 1 makes the next insert receive 1. Deleting rows and changing the counter are separate operations. TRUNCATE TABLE also resets the counter, empties the whole table and can cause an implicit commit. Existing references in other tables, logs or systems can collide when old IDs are reused. MariaDB Docs · TRUNCATE TABLE

Troubleshoot unexpected IDs

Start with SHOW CREATE TABLE to check the attribute, type, index and engine. Then check the session’s step, offset, SQL mode and writes from other connections. Keep production replication and cluster settings aligned with that environment. When using a connection pool, check the insert succeeded and retrieve its key before returning the connection.