pythonintermediate

SQLAlchemy Bulk Insert with Upsert

Efficiently bulk-insert rows with conflict resolution using SQLAlchemy Core and PostgreSQL.

python
from sqlalchemy import create_engine, Table, MetaData
from sqlalchemy.dialects.postgresql import insert

engine = create_engine('postgresql://user:pass@localhost/db')
meta = MetaData()
meta.reflect(bind=engine)
table = meta.tables['events']

rows = [
    {'id': 1, 'name': 'Alice', 'score': 95},
    {'id': 2, 'name': 'Bob',   'score': 87},
]

stmt = insert(table).values(rows)
stmt = stmt.on_conflict_do_update(
    index_elements=['id'],
    set_={'score': stmt.excluded.score},
)
with engine.begin() as conn:
    conn.execute(stmt)
    print('Upserted', len(rows), 'rows')

Use Cases

  • idempotent loads
  • incremental ETL
  • data synchronisation

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.