Sling Academy
Home/SQLAlchemy/SQLAlchemy: Get the ID of the Last Inserted Row

SQLAlchemy: Get the ID of the Last Inserted Row

Last updated: January 03, 2024

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.

Next Article: SQLAlchemy: Get a list of all tables

Previous Article: Weighted Random Selection in SQLAlchemy: An In-Depth Guide

Series: SQLAlchemy Tutorials: From Basic to Advanced

SQLAlchemy

You May Also Like

  • SQLAlchemy: Counting rows for each category (2 approaches)
  • SQLAlchemy: Adding a calculated column to SELECT query
  • SQLAlchemy: Grouping data on multiple columns
  • SQLAlchemy: How to temporarily delete a row
  • SQLAlchemy Composite Indexes: The Complete Guide
  • Full-Text Search in SQLAlchemy: The Ultimate Guide
  • SQLAlchemy: What if you don’t close database connections?
  • SQLAlchemy: How to Remove FOREIGN KEY Constraints (2 Ways)
  • SQLAlchemy: How to Create and Use Temporary Tables
  • SQLAlchemy: Saving Categories and Subcategories in the Same Table
  • SQLAlchemy: How to Automatically Delete Old Records
  • Weighted Random Selection in SQLAlchemy: An In-Depth Guide
  • SQLAlchemy: created_at and updated_at columns
  • How to Use Regular Expressions in SQLAlchemy
  • SQLAlchemy: Ways to Find Results by a Keyword
  • SQLAlchemy: How to Connect to MySQL Database
  • SQLAlchemy: How to Bulk Insert Data into a Table
  • SQLAlchemy: How to Update a Record by ID
  • SQLAlchemy: Singular vs Plural Table Names