SQLite AUTOINCREMENT
Automatic Numbers
In SQLite, you do not need a special keyword to get automatic numbers. An INTEGER PRIMARY KEY column gets the next number automatically:
Example
CREATE TABLE IF NOT EXISTS Pets (
PetID INTEGER PRIMARY KEY,
Name TEXT
);
INSERT INTO Pets (Name)
VALUES ('Rex'), ('Bella'), ('Max');
SELECT * FROM Pets;
Try it Yourself »
Numbers Can Be Used Again
The next number is one more than the largest number in the table. If you delete the record with the largest number, its number can be used again:
Example
CREATE TABLE Pets (
PetID INTEGER PRIMARY KEY,
Name TEXT
);
INSERT INTO Pets (Name)
VALUES ('Rex'), ('Bella'), ('Max');
DELETE FROM Pets WHERE PetID = 3;
INSERT INTO Pets (Name) VALUES ('Luna');
SELECT * FROM Pets;
Try it Yourself »
Luna gets PetID 3, the same number that Max had. If the example gives an error, the Pets table is already there: click "Restore Database" and try again.
The AUTOINCREMENT Keyword
With AUTOINCREMENT, a number is never used again, even if the record is deleted:
Example
CREATE TABLE IF NOT EXISTS Animals (
AnimalID INTEGER PRIMARY KEY AUTOINCREMENT,
Name TEXT
);
INSERT INTO Animals (Name)
VALUES ('Rex'), ('Bella'), ('Max');
DELETE FROM Animals WHERE Name = 'Max';
INSERT INTO Animals (Name) VALUES ('Luna');
SELECT * FROM Animals;
Try it Yourself »
Luna gets a new number, not the number that Max had.
Note: AUTOINCREMENT makes inserts a little slower. Only use it when you must be sure that a number is never used again.
Start From Another Number
To start the numbers from 100, insert the first record with the number 100. The next records get 101, 102 and so on:
INSERT INTO Pets (PetID, Name) VALUES (100, 'Rex');