What is an 'AUTO_INCREMENT' field, and how is it used?

Instruction: Using MySQL, explain AUTO_INCREMENT and give a complete table/insert example. Discuss uniqueness, gaps, generated-key retrieval and dialect differences.

Context: This question assesses the candidate's knowledge of the AUTO_INCREMENT attribute, which is used to generate a unique identifier for new rows.

Updated

Official answer

AUTO_INCREMENT is MySQL syntax for automatic numeric allocation, commonly used with a primary key. In a fresh MySQL table:

CREATE TABLE items (
  item_id bigint NOT NULL AUTO_INCREMENT PRIMARY KEY,
  name varchar(100) NOT NULL
);
INSERT INTO items (name) VALUES ('Notebook'), ('Pen');
SELECT item_id, name FROM items ORDER BY item_id;

With the normal default increment and offset and no prior rows or explicit overrides, the generated IDs are 1 and 2. Other configurations can differ. Use the driver's generated-key facility or the documented connection-specific LAST_INSERT_ID behavior where appropriate; do not infer an ID with MAX(id).

The primary key enforces stored uniqueness. Generated IDs can have gaps and do not establish creation or commit order. Choose a type with adequate capacity and define any distributed allocation strategy explicitly. PostgreSQL identity columns and SQL Server IDENTITY use different syntax and rules; do not copy AUTO_INCREMENT into every SQL dialect.

Reference: MySQL AUTO_INCREMENT.

Related Questions