SQLite in Python: get the ID of the last inserted row
Codemia Knowledge Hub ·
After running an INSERT with Python's sqlite3 module, read cursor.lastrowid to get the ID of the row you just inserted. That value is the row's rowid, SQLite's unique integer key.
SQLite's rowid and primary keys
- SQLite assigns a
rowidto each row. - You can define an
INTEGER PRIMARY KEYcolumn to take the place ofrowid. - If no such primary key is defined, SQLite uses
rowid.
Because rowid uniquely identifies each record, it is what you use to retrieve, update or delete specific rows.
Steps with the sqlite3 module
sqlite3 is part of Python's standard library. The process is:
- Connect to the database: open an existing database or create a new one.
- Create a cursor: this executes SQL commands.
- Insert the row: run an
INSERT INTOstatement. - Read the ID:
cursor.lastrowidholds the ID of the last inserted row.
Code for all four steps
The following code connects to a database file (creating it if needed), inserts a row and reads its ID:
Because id is an INTEGER PRIMARY KEY, it is an alias for rowid, so cursor.lastrowid is the new row's id.
What to do with the returned ID
- Foreign key relations: use the
rowidto insert related rows into another table and keep them linked. - Reporting: log or track inserted records by their
rowid. - Follow-up queries: use the
rowidto query or modify the record later.
Threads, transactions and batch inserts
- Thread safety: SQLite connections are not thread-safe by default. Pass
check_same_thread=Falseif you need multithreading. - Transactions: SQLite wraps commands in a transaction automatically. Call
conn.commit()to finalize it when you run multiple operations. - Performance: for batch inserts, use transactions and bulk insert strategies.
Related reading
- How to retrieve JSON data from MySQL?
- How to retrieve the current version of a MySQL database management system DBMS?
- How to retrieve the timestamp from cassandra?
- How to return a custom object from a Spring Data JPA GROUP BY query
- How to return binary data from lambda function in AWS in Python?
- How to reversibly store and load a Pandas dataframe to/from disk
- How to return a custom response pojo when request body fails validations that are defined using Bean Validation/Hibernate Validator?
- How to return the inserted item in dynamoDB
System design interview problems on this topic
- Design a Distributed OLTP Database: solution and walkthrough
- Design a Wide Column Database: solution and walkthrough
- Design a Key Value Store: solution and walkthrough
- Design a Web Cache: solution and walkthrough

System Design Fundamentals
Build a strong foundation in designing scalable, reliable distributed systems.
View the courseSystem Design practice on Codemia
Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.