skip to content

In SQLAlchemy 2.1, what does session.execute(insert(Product), list_of_dicts) do, and what does it skip compared with adding Product objects?

level: middleimportance: should knowfreq 30%

answer

  1. parameters passed separately
  2. bulk INSERT mode
  3. attribute names, not column names
  4. no objects to hand to events
  5. returning(Product) for objects back

basics

~20 s

Passing insert(Product) and a separate list of dicts to Session.execute() selects ORM bulk INSERT mode: rows go out as executemany batches keyed by mapped attribute names, with no Product objects, relationship cascades or mapper events.

solid answer

~40 s

When `Session.execute()` gets an ORM `insert(Product)` plus a list of dicts as its parameters, SQLAlchemy uses **bulk INSERT mode**. Each dict is keyed by mapped attribute names; dicts with different key sets are grouped into separate INSERT statements, and by default a `None` value moves its row into a batch that leaves that column out, so server defaults still fire (`render_nulls=True` sends NULL instead). No `Product` objects are created, nothing enters the identity map, relationships do not cascade, and `before_insert` listeners and `@validates` methods do not run. Python-side `default=` values on columns still apply. Add `.returning(Product)` and use `session.scalars()` to get persistent objects back, with `sort_by_parameter_order=True` when order must match the input.

code

python · 37 lines
python
from decimal import Decimal

from sqlalchemy import Numeric, create_engine, event, insert
from sqlalchemy.orm import DeclarativeBase, Mapped, Session, mapped_column


class Base(DeclarativeBase):
    pass


class Product(Base):
    __tablename__ = "product"
    id: Mapped[int] = mapped_column(primary_key=True)
    sku: Mapped[str] = mapped_column(unique=True)
    price: Mapped[Decimal] = mapped_column(Numeric(10, 2))
    discontinued: Mapped[bool] = mapped_column(default=False)


@event.listens_for(Product, "before_insert")
def stamp(mapper, connection, target):
    print("before_insert for", target.sku)  # never printed by the bulk path


engine = create_engine("sqlite://")
Base.metadata.create_all(engine)
feed = [
    {"sku": "SKU-1", "price": Decimal("9.99")},
    {"sku": "SKU-2", "price": Decimal("4.50")},
]

with Session(engine) as session, session.begin():
    session.execute(insert(Product), feed)  # no objects, one executemany
    created = session.scalars(
        insert(Product).returning(Product, sort_by_parameter_order=True),
        [{"sku": "SKU-3", "price": Decimal("1.25")}],
    ).all()
    print(created[0].id, created[0] in session)  # 3 True

go deeper

for a junior

Recall the call shape, insert(Model) plus a list of dicts passed to Session.execute(), and that it creates no objects.

for a middle

Explain the skipped features: events, @validates, cascades and identity-map entries, and how key sets and None values decide the batches.

for a senior

Show you notice when an audit listener silently stopped running after a switch to bulk inserts, and how you restore the value.

for a principal

Weigh where a team allows bulk inserts, given that any invariant kept in mapper events or validators is bypassed on that path.

## How bulk INSERT mode is chosen SQLAlchemy 2.1 decides the mode from **how the rows are passed**. An `insert(Product)` handed to `Session.execute()` together with a list of dicts as the second argument, the `params`, switches the ORM into **bulk INSERT mode**, which is built to send many rows with as little Python work per row as possible. ```python session.execute( insert(PriceAudit), [ {"product_id": 17, "old_price": 9.99, "new_price": 10.49}, {"product_id": 18, "old_price": 4.50, "new_price": 4.75}, ], ) ``` The emitted SQL is a single parameterized INSERT run as an **executemany**, one parameter set per dict. Since 2.0 this is the replacement for the legacy `Session.bulk_insert_mappings()`, and the Session autoflushes pending objects before running it. ## What the dicts may contain - **Keys are mapped attribute names**, not database column names, when the two differ. In 1.x an `insert()` passed to the Session was read Core-style with column names; the 2.0 behaviour is kept in 2.1. The execution option `dml_strategy="raw"` restores the Core interpretation. - **Dicts may have different keys.** The ORM groups rows by key set and sends one INSERT per group, keeping row order. A plain Core `insert()` with an executemany list builds its VALUES clause from the first dict only, so mixed keys behave differently there. - **`None` values split batches by default.** A row whose value is `None` is sent in an INSERT that omits the column, so a server-side default can apply. Rows with scattered `None` values therefore break one big batch into many small ones. The execution option `render_nulls=True` sends explicit NULLs and keeps one batch. - **Python-side column defaults still apply**: a `mapped_column(default=...)` callable fills a missing key, because that default belongs to the Core column. Three audit rows where the middle one has `note=None` show the grouping in the echo log: ```sql INSERT INTO price_audit (product_id, old_price, new_price, note) VALUES (?, ?, ?, ?) -- (17, 9.99, 10.49, 'feed') INSERT INTO price_audit (product_id, old_price, new_price) VALUES (?, ?, ?) -- (18, 4.5, 4.75) INSERT INTO price_audit (product_id, old_price, new_price, note) VALUES (?, ?, ?, ?) -- (19, 2.0, 2.1, 'feed') ``` Row order is kept, so the batches follow the input; a list that alternates between key sets produces many tiny statements. Sorting or normalizing the dicts before the call, so every dict has the same keys, keeps the batch whole. ## What the bulk path skips | Feature | `session.add_all(objects)` | `session.execute(insert(Product), dicts)` | |---|---|---| | Product objects created and tracked | yes | no | | Relationship cascade (children saved, foreign keys filled) | yes | no | | `before_insert` / `after_insert` mapper events | yes | no | | `@validates` and attribute events | yes | no | | Generated primary keys copied onto objects | yes | only with `.returning()` | | `do_orm_execute` session event | no | yes, once per statement | The skipped rows matter in a pricing job: if a `before_insert` listener stamps `created_by` on audit rows, the bulk path writes those rows without it. Put such values in the dicts, give the column a Python-side or server default, or intercept the statement with `do_orm_execute`. ## Getting rows and objects back `insert(Product).returning(Product)` turns the bulk insert into one that returns rows. Run through `session.scalars()`, it yields **persistent `Product` objects** that are in the identity map, as if loaded by a SELECT. Things to know: 1. RETURNING with many parameter sets works on PostgreSQL and SQLite, but not on MySQL, which lacks INSERT ... RETURNING. 2. Most databases do not promise that RETURNING rows come back in input order. `returning(..., sort_by_parameter_order=True)` makes SQLAlchemy guarantee it, using a sentinel where it can; on SQLite with server-generated keys it degrades to one INSERT per row. 3. `.returning(Product.id)` is cheaper when you only need the new keys. ## When not to use it Use the bulk path for **flat rows** whose foreign keys you already know, such as audit rows for products that exist. When rows form a graph, for example a new supplier and its products whose `supplier_id` the ORM must fill in, `add_all()` and the unit of work do that work for you.

  • Why did a 200,000-row ORM bulk insert in SQLAlchemy turn into thousands of small INSERT statements?
    The ORM groups rows by key set and, by default, moves a row with a `None` value into an INSERT that omits that column. Dicts with differing keys or scattered `None`s therefore fragment the batch. Give every dict the same keys and pass `render_nulls=True` as an execution option when explicit NULL is acceptable, accepting that server defaults then no longer apply to those columns.
  • How do you get generated ids back from a SQLAlchemy bulk insert in the same order as the input dicts?
    Use `insert(Product).returning(Product.id, sort_by_parameter_order=True)` with `session.scalars()`. SQLAlchemy then guarantees RETURNING rows match input order, batching with a sentinel where the backend allows it and falling back to one INSERT per row otherwise, as on SQLite with server-generated keys. MySQL lacks INSERT ... RETURNING, so this form is not available there.

  • The dict keys must be database column names, as in the Table definition.
  • A before_insert listener runs once for each dict in the list.
  • Every dict must have exactly the same keys or the call fails.
  • Bulk insert also saves related objects through the relationship cascade.
  • Rows inserted this way are in the identity map afterwards without RETURNING.

Assumes SQLAlchemy 2.1; since 2.0 an ORM insert() given to Session.execute() with a list of dicts runs as bulk INSERT keyed by attribute names, where 1.x read it Core-style by column names.