Consider this MySQL table and inserts:
CREATE TABLE users (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(20));
INSERT INTO users (name) VALUES ('Alice'), ('Bob');
INSERT INTO users (id, name) VALUES (5, 'Charlie');
INSERT INTO users (name) VALUES ('David');What will be the id of 'David'?
CREATE TABLE users (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(20)); INSERT INTO users (name) VALUES ('Alice'), ('Bob'); INSERT INTO users (id, name) VALUES (5, 'Charlie'); INSERT INTO users (name) VALUES ('David'); SELECT * FROM users ORDER BY id;
Remember that AUTO_INCREMENT will use the highest existing value plus one.
After inserting 'Charlie' with id 5, the AUTO_INCREMENT counter moves to 6. So 'David' gets id 6.
Given a table with AUTO_INCREMENT primary key, if you delete the row with the highest id, what will be the next inserted row's id?
Think about how AUTO_INCREMENT keeps track internally.
Deleting rows does not reset AUTO_INCREMENT. It continues from the highest value it has seen.
You want to reset the AUTO_INCREMENT counter of a table named orders to 1. Which SQL statement is correct?
Look for the correct syntax to alter table properties.
Only ALTER TABLE with AUTO_INCREMENT = value is valid syntax to reset the counter.
You want to keep AUTO_INCREMENT values continuous without gaps after deleting rows. Which approach is best?
Think about how AUTO_INCREMENT works and what causes gaps.
Deleting rows creates gaps. Marking rows inactive avoids gaps without resetting AUTO_INCREMENT.
Given this table and inserts:
CREATE TABLE products (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(20));
INSERT INTO products (id, name) VALUES (1, 'Pen');
INSERT INTO products (name) VALUES ('Pencil');
INSERT INTO products (id, name) VALUES (1, 'Eraser');Why does the last insert fail?
CREATE TABLE products (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(20)); INSERT INTO products (id, name) VALUES (1, 'Pen'); INSERT INTO products (name) VALUES ('Pencil'); INSERT INTO products (id, name) VALUES (1, 'Eraser');
Check the primary key constraints and inserted values.
Inserting id 1 again causes a duplicate key error because id 1 already exists.