Databases python Intermediate

SQLAlchemy Bulk Insert with Chunks

Insert thousands of rows efficiently using bulk_insert_mappings in chunks.

python
from sqlalchemy.orm import Session
from models import Module

def bulk_seed(rows: list[dict], session: Session, chunk: int = 500):
    for i in range(0, len(rows), chunk):
        session.bulk_insert_mappings(Module, rows[i:i+chunk])
        session.commit()
    print(f"Inserted {len(rows)} rows")

# Usage
bulk_seed(prepared_data, db_session)

Prerequisites

  • sqlalchemy >= 1.4

Pro Tips

  • → Disable autoflush for large inserts: session.autoflush = False.

Was this module useful?

Share your experience — it helps the team improve.

Leave Feedback

Commercial Licensing

Acquire a production access token or template license for enterprise deployment.

Module Info

Language
python
Level
Intermediate
Read time
3 min
Published
Jan 2026
License
Commercial License

Newsletter

New modules every week, directly to your inbox.