Almost every table needs an ID that is unique for each row: an order number, a ticket number, a patient ID. You could work out the next number yourself, but two users saving at the same moment might pick the same one. Instead, let the database hand out IDs automatically. This lesson shows how SQLite does it, how other databases write it, and why gaps in the numbers are normal.
In this lesson you will learn
- How
INTEGER PRIMARY KEYcreates IDs in SQLite - How to get the ID of the row you just inserted
- What
AUTOINCREMENTchanges - The syntax in MySQL, PostgreSQL and SQL Server
- Why IDs have gaps, and when to use UUIDs
You should know CREATE TABLE and constraints and INSERT.
Automatic IDs in SQLite
In SQLite, a column declared exactly as INTEGER PRIMARY KEY becomes the row’s built-in rowid. If you leave it out of an INSERT, SQLite fills it with one more than the largest ID in the table.
CREATE TABLE tickets (
id INTEGER PRIMARY KEY, -- SQLite fills this in
subject TEXT NOT NULL
);
INSERT INTO tickets (subject) VALUES ('Login problem'), ('Wrong invoice'), ('Refund');
SELECT id, subject FROM tickets;
SELECT last_insert_rowid() AS newest_id;
-- Delete the newest ticket, then add another one
DELETE FROM tickets WHERE id = 3;
INSERT INTO tickets (subject) VALUES ('Password reset');
SELECT id, subject FROM tickets;
Output
+----+---------------+
| id | subject |
+----+---------------+
| 1 | Login problem |
| 2 | Wrong invoice |
| 3 | Refund |
+----+---------------+
(3 rows)
+-----------+
| newest_id |
+-----------+
| 3 |
+-----------+
(1 row)
+----+----------------+
| id | subject |
+----+----------------+
| 1 | Login problem |
| 2 | Wrong invoice |
| 3 | Password reset |
+----+----------------+
(3 rows)
- The
INSERTlists onlysubject, so the IDs 1, 2, 3 were chosen by SQLite. last_insert_rowid()returns the ID of the latest insert on this connection. Programs use it to, for example, add order lines straight after creating an order. Newer SQLite (3.35+), PostgreSQL and others also supportINSERT … RETURNING id.- After ticket 3 was deleted, the new ticket also got ID 3. Without
AUTOINCREMENT, SQLite may reuse the number of a deleted top row.
AUTOINCREMENT: Never Reuse
CREATE TABLE invoices (
id INTEGER PRIMARY KEY AUTOINCREMENT,
amount INTEGER NOT NULL
);
INSERT INTO invoices (amount) VALUES (500), (750), (1200);
DELETE FROM invoices WHERE id = 3;
INSERT INTO invoices (amount) VALUES (900);
SELECT id, amount FROM invoices;
-- AUTOINCREMENT remembers the highest id ever used here
SELECT name, seq FROM sqlite_sequence;
Output
+----+--------+
| id | amount |
+----+--------+
| 1 | 500 |
| 2 | 750 |
| 4 | 900 |
+----+--------+
(3 rows)
+----------+-----+
| name | seq |
+----------+-----+
| invoices | 4 |
+----------+-----+
(1 row)
With AUTOINCREMENT, SQLite records the highest ID ever used in the internal table sqlite_sequence. Invoice 3 was deleted, but the next invoice is 4, not 3. Use it when a reused number could cause confusion, for example invoices or receipts that were already printed. It is slightly slower, so the SQLite documentation suggests leaving it off unless you need it.
Other Databases
| Database | Column definition | Get the new ID |
|---|---|---|
| SQLite | id INTEGER PRIMARY KEY (optionally AUTOINCREMENT) | last_insert_rowid() or RETURNING id |
| MySQL | id INT AUTO_INCREMENT PRIMARY KEY | LAST_INSERT_ID() |
| PostgreSQL | id INT GENERATED ALWAYS AS IDENTITY PRIMARY KEY (older code uses SERIAL) | RETURNING id |
| SQL Server | id INT IDENTITY(1,1) PRIMARY KEY | SCOPE_IDENTITY() or OUTPUT inserted.id |
PostgreSQL and SQL Server also have stand-alone sequences: objects that hand out the next number on request with nextval('name') or NEXT VALUE FOR name. Several tables can share one sequence.
Gaps Are Normal
Do not expect IDs to be perfectly continuous. Gaps appear when rows are deleted, when a transaction that took a number is rolled back, and in some databases after a restart. An ID’s only job is to be unique. If you need numbers without gaps, such as a cheque book serial, create them separately and carefully, not from the primary key.
Integers or UUIDs?
Integer IDs are small, fast and easy to read. A UUID is a 128-bit random-looking value such as 3f2b9c1e-…. UUIDs can be created on any device without asking the database, and they do not reveal how many rows exist. They are bigger and harder to read. Many apps use integers inside the database and UUIDs in public links.
Common Mistakes
- Calculating
MAX(id) + 1yourself. Two users can get the same number at the same time. Let the database do it. - Writing
INT PRIMARY KEYin SQLite. Only the exact wordsINTEGER PRIMARY KEYcreate the automatic rowid alias. - Treating ID order as time order. Use a timestamp column to know when a row was created.
- Showing raw IDs in public URLs when they reveal private counts, such as how many orders a shop gets.
Practice Exercises
Exercise 1. A table with INTEGER PRIMARY KEY (no AUTOINCREMENT) has IDs 1, 2 and 5. Row 5 is deleted, then a new row is inserted. What ID will it most likely get?
Show answer
3, one more than the current largest ID, which is now 2.
Exercise 2. Write a MySQL CREATE TABLE for a receipts table with an automatic ID and an amount.
Show answer
CREATE TABLE receipts (
id INT AUTO_INCREMENT PRIMARY KEY,
amount DECIMAL(10,2) NOT NULL
);
Frequently Asked Questions
How do I create an auto-increment column in SQLite?
Declare the column as INTEGER PRIMARY KEY. When you insert a row without giving that column, SQLite assigns the next number automatically. Add AUTOINCREMENT only if numbers of deleted rows must never be reused.
Why are there gaps in my auto-increment IDs?
Gaps come from deleted rows, rolled-back transactions and some server restarts. This is normal. An ID only needs to be unique, not continuous.
Summary
- Let the database generate IDs; never calculate them yourself.
- SQLite:
INTEGER PRIMARY KEY; addAUTOINCREMENTto stop reuse. - MySQL uses
AUTO_INCREMENT, PostgreSQLIDENTITY, SQL ServerIDENTITY(1,1). - Gaps are normal; use timestamps for time order and consider UUIDs for public IDs.
Next: SQL Generated Columns.
