How to retrieve inserted id after inserting row in SQLite using Python?
System Design practice on Codemia
Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.
Retrieving the Inserted Row ID in SQLite with Python
In SQLite, every row in a table typically has a unique integer key called `rowid`, which can be automatically incremented and used as a primary key. When you insert a new row into a table, you might want to retrieve this ID immediately for further operations. This article explores how to accomplish this efficiently using Python.
SQLite's `rowid` and Primary Keys
By default, if a table does not have an explicit integer primary key, SQLite automatically generates a `rowid` for each row. Here’s a brief overview:
- SQLite assigns a `rowid` to each row.
- You can explicitly define an INTEGER PRIMARY KEY to replace `rowid`.
- Automatically, `rowid` is used if no primary key is present or specified.
This `rowid` is crucial for many operations like retrieving, updating, or deleting specific rows as it uniquely identifies each record.
Using Python's SQLite Module
Python's standard library includes `sqlite3`, which allows easy interaction with SQLite databases. The process of inserting a row and retrieving its ID includes several steps:
- Establish a Connection to the Database: Either connect to an existing database or create a new one.
- Create a Cursor: This allows you to execute SQL commands.
- Insert the Row: Use the `INSERT INTO` SQL command.
- Retrieve the Last Inserted ID: Use `cursor.lastrowid` to get the ID of the last inserted row.
Here's a detailed guide with code snippets.
Step-by-Step Guide
1. Connect to the SQLite Database
First, ensure you have the `sqlite3` module available in your Python environment. The following Python code connects to an SQLite database:
- Foreign Key Relations: Utilize the retrieved `rowid` to insert related data into another table, maintaining integrity between rows.
- Data Reporting: Log or track inserted records by storing the `rowid`.
- Dynamic Queries: Use the `rowid` for subsequent querying or record manipulation.
- Thread Safety: SQLite connections are not thread-safe by default. Use `check_same_thread=False` if multithreading is necessary.
- Transactions: SQLite automatically wraps commands in a transaction. Use `conn.commit()` to manually finalize it for multiple operations.
- Performance: For batch inserts, consider employing transactions and bulk insert strategies to enhance performance.
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 Fundamentals
Build a strong foundation in designing scalable, reliable distributed systems.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
System Design practice on Codemia
Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.