SQLAlchemy: Get the ID of the Last Inserted Row

Updated: January 3, 2024 By: Guest Contributor Post a comment

Introduction

Understanding how to retrieve the ID of the last inserted row is crucial for database operations. This tutorial explores how to accomplish this using SQLAlchemy, a powerful and flexible ORM (Object-Relational Mapping) tool for Python.

Basic Usage

Let’s start with the most straightforward scenario. In SQLAlchemy, when you add a new object to the session and commit, you can generally access the new primary key directly from the object.

# Import SQLAlchemy's functions
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from yourapplication.database import model

# Create an engine and bind it
default_engine = create_engine('sqlite:///yourapplication.db')

# Create a new session
default_session = sessionmaker(bind=default_engine)()

# Instantiate your model
new_user = model.User(name='John Doe', email='[email protected]')

# Add the new object to the session
default_session.add(new_user)

# Commit the session to write the changes to the database
default_session.commit()

# Access the generated ID
print(new_user.id)

In the code above, new_user.id will contain the ID of the newly inserted row after the session has been committed.

Retrieving IDs in Bulk Inserts

Retrieving IDs becomes slightly more challenging when you perform bulk inserts. However, SQLAlchemy offers a way to handle this efficiently. Consider the following example:

# Prepare a bulk insert
users_to_add = [model.User(name=user_name, email=user_email) for user_name, user_email in users_data]

# Perform the bulk insert
yourapplication_default_session.add_all(users_to_add)

# Commit the session
default_session.commit()

# IDs are now populated
new_ids = [user.id for user in users_to_add]
print(new_ids)

After committing the session, each object in users_to_add will have the .id attribute set to the value assigned by the database.

Advanced: Using the ‘returning’ Clause

In some use cases, especially when dealing with advanced SQL features or legacy schemas, you may need to use the ‘returning’ clause to explicitly ask for inserted IDs. To use this feature, you would typically write something like this:

# Custom insert with 'returning' using SQLAlchemy Core
from sqlalchemy import insert

stmt = insert(model.User).values(name='Jane Doe', email='[email protected]')
stmt = stmt.returning(model.User.id)

# Execute the statement and fetch the result
new_id = default_session.execute(stmt).first()[0]
print(new_id)

This returns the ID directly as part of the insert statement execution.

Conclusion

In this tutorial, we explored a variety of methods to obtain the ID of the last inserted row using SQLAlchemy. By understanding these techniques, you can implement robust and efficient solutions to interact with your database. As always, consider your specific use case when choosing the approach, and remember to write safe and maintainable code.