SQLite
Python
Insert ID
Database
SQL

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 rowid to each row.
  • You can define an INTEGER PRIMARY KEY column to take the place of rowid.
  • 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:

  1. Connect to the database: open an existing database or create a new one.
  2. Create a cursor: this executes SQL commands.
  3. Insert the row: run an INSERT INTO statement.
  4. Read the ID: cursor.lastrowid holds 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:

python
1import sqlite3
2
3conn = sqlite3.connect("example.db")
4cursor = conn.cursor()
5cursor.execute(
6    "CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT)"
7)
8cursor.execute("INSERT INTO users (name) VALUES (?)", ("Alice",))
9conn.commit()
10
11print(cursor.lastrowid)  # e.g. 1
12conn.close()

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 rowid to insert related rows into another table and keep them linked.
  • Reporting: log or track inserted records by their rowid.
  • Follow-up queries: use the rowid to 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=False if 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.

Course
Beginner
27 lessons
10 hours
System Design Fundamentals

Build a strong foundation in designing scalable, reliable distributed systems.

View the course
System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design