How do you upsert products by SKU with SQLAlchemy's postgresql.insert() and on_conflict_do_update(), and what does stmt.excluded provide?
answer
- the dialect's own insert()
- a conflict target is required
- set_ is a dict you write
- excluded is the proposed row
- MySQL calls it inserted
basics
~10 sImport insert from sqlalchemy.dialects.postgresql, then call on_conflict_do_update(index_elements=[products.c.sku], set_={...}). Inside set_, stmt.excluded.<column> refers to the value the conflicting INSERT row proposed.
solid answer
~40 sThe generic `sqlalchemy.insert()` has no upsert methods; the PostgreSQL one does: `stmt = postgresql.insert(products)`. Then `stmt.on_conflict_do_update(index_elements=[products.c.sku], set_={'price_cents': stmt.excluded.price_cents})` renders `ON CONFLICT (sku) DO UPDATE SET price_cents = excluded.price_cents`. Exactly one of `constraint=` (a unique constraint's name) or `index_elements=` is required, `set_` must be a non-empty dict, and an optional `where=` limits which conflicting rows are updated. `stmt.excluded` is a column collection aliasing the table as `excluded`, so you must keep a reference to the statement to build `set_`. `on_conflict_do_nothing()` makes the target optional. SQLite's `insert()` has the same methods; MySQL's has `on_duplicate_key_update()` with `stmt.inserted`. Add `returning()` and pass a list of dicts to batch it.
code
python · 29 linesfrom sqlalchemy import Boolean, Column, Integer, MetaData, String, Table
from sqlalchemy.dialects import postgresql
metadata = MetaData()
products = Table(
"products", metadata,
Column("id", Integer, primary_key=True),
Column("sku", String(32), unique=True, nullable=False),
Column("name", String(200), nullable=False),
Column("price_cents", Integer, nullable=False),
Column("active", Boolean, nullable=False, default=True),
)
# Build in two steps: set_ needs stmt.excluded from the same statement.
stmt = postgresql.insert(products)
stmt = stmt.on_conflict_do_update(
index_elements=[products.c.sku],
set_={
"name": stmt.excluded.name,
"price_cents": stmt.excluded.price_cents,
"active": True,
},
where=products.c.price_cents != stmt.excluded.price_cents,
).returning(products.c.id, products.c.sku)
print(stmt.compile(dialect=postgresql.dialect()))
# Executed as conn.execute(stmt, rows) with a list of dicts, this runs
# through insertmanyvalues batching and returns a row per inserted or
# updated product.go deeper
Recall that upserts need the dialect's own insert(), and that PostgreSQL and SQLite use on_conflict_do_update while MySQL uses on_duplicate_key_update.
Explain the required conflict target, how set_ and excluded render, why the statement is built in two steps, and how where= skips unchanged rows.
Show you batch the upsert with a list of dicts and returning(), know the ValueError guards, and remember that Column onupdate values are not applied in set_.
Decide whether a shared data layer hides dialect upserts behind one function per backend, and how the team keeps conflict targets aligned with the unique constraints in the schema.
## The dialect-specific `insert()` An **upsert** inserts a row or, when a unique key already exists, updates it. SQL dialects spell it differently, so SQLAlchemy does not put it on the generic `sqlalchemy.insert()`; calling `on_conflict_do_update` on that object raises `AttributeError`. Each supporting dialect ships its own `insert()` function returning an `Insert` subclass: - `sqlalchemy.dialects.postgresql.insert()` adds `on_conflict_do_update()`, `on_conflict_do_nothing()` and `excluded`. - `sqlalchemy.dialects.sqlite.insert()` adds the same methods and `excluded`. - `sqlalchemy.dialects.mysql.insert()` (MySQL and MariaDB) adds `on_duplicate_key_update()` and `inserted`. A statement built with one dialect's `insert()` compiles only for that dialect; compiling the PostgreSQL construct for MySQL raises `UnsupportedCompilationError`. ## The arguments of `on_conflict_do_update()` | Argument | Meaning | |---|---| | `index_elements` | columns (names or `Column` objects) or expressions that infer the unique index to arbitrate on, e.g. `[products.c.sku]` | | `constraint` | the name of a unique or exclusion constraint, or the constraint object; mutually exclusive with `index_elements` | | `index_where` | extra criteria for inferring a partial unique index | | `set_` | a dict of column (name or `Column`) to value or expression, rendered as `DO UPDATE SET` | | `where` | a condition after `DO UPDATE SET`; conflicting rows that fail it are left unchanged | Rules SQLAlchemy enforces when you build the statement: 1. Give exactly one of `constraint` or `index_elements`. Neither raises `ValueError: Either constraint or index_elements, but not both, must be specified unless DO NOTHING`; both raises `ValueError: 'constraint' and 'index_elements' are mutually exclusive`. 2. `set_` must be a non-empty dict or a column collection; `{}` raises `ValueError: set parameter dictionary must not be empty`. 3. One ON CONFLICT per PostgreSQL statement; a second call raises `InvalidRequestError` ("This Insert construct already has an ON CONFLICT clause established"). ## The `excluded` namespace `stmt.excluded` is a column collection over an alias of the table named `excluded`, so `stmt.excluded.price_cents` renders as `excluded.price_cents`: the value the INSERT tried to write. A bare `products.c.price_cents` in `set_` or `where` means the value already stored. Because `excluded` belongs to the statement object, build in two steps: `stmt = postgresql.insert(products)`, then `stmt = stmt.on_conflict_do_update(..., set_={"name": stmt.excluded.name})`. Plain Python values in `set_` become bound parameters. ## Doing nothing instead `on_conflict_do_nothing()` takes the same optional `constraint`, `index_elements` and `index_where`; with no target it skips a row that conflicts with any unique constraint. Use it when an existing SKU must never be overwritten. ## Running it for the nightly import The upsert is still an `Insert`, so it accepts a list of dicts: `conn.execute(stmt, rows)`. With `.returning(products.c.id, products.c.sku)` the insertmanyvalues feature batches it and returns a row for each product inserted or updated; a `where=` that skips unchanged rows also keeps them out of RETURNING. The ON CONFLICT clause does not take a table's `Column(onupdate=...)` into account; any timestamp you want refreshed must be listed in `set_` yourself. ## SQLite and MySQL equivalents | Dialect | Method | Incoming-row namespace | Conflict target | |---|---|---|---| | PostgreSQL | `on_conflict_do_update()` / `on_conflict_do_nothing()` | `stmt.excluded` | `constraint` or `index_elements` | | SQLite | `on_conflict_do_update()` / `on_conflict_do_nothing()` | `stmt.excluded` | `index_elements` only; 2.1 allows several ON CONFLICT clauses | | MySQL, MariaDB | `on_duplicate_key_update(**kw)` | `stmt.inserted` | none; any unique key triggers it | MySQL's `inserted` renders as `VALUES(col)`, or as a row alias (`AS new ... new.col`) when the server is MySQL 8.0.20 or later. It is named `inserted` so it does not clash with `Insert.values()`. ## Reviewing an upsert - **The target matches a real unique constraint or index.** `index_elements=[products.c.sku]` only works if `sku` carries a unique constraint or unique index; naming the constraint with `constraint=` makes the dependency explicit. - **`set_` leaves the key alone.** Updating `sku` from `excluded.sku` is pointless and invites mistakes; list only the columns the feed owns. - **Keys may be strings or `Column` objects.** `set_={products.c.price_cents: ...}` and `set_={"price_cents": ...}` render the same SET entry. - **Literal values are parameters.** `"active": True` becomes a bound parameter (`%(param_1)s` in the compiled SQL), not inlined text. - **Duplicates inside one batch are the data's problem.** PostgreSQL refuses to update the same row twice in one statement, so de-duplicate SKUs before calling `execute()`.
- When would you name the constraint instead of listing index_elements?When the arbiter is easier to name than to infer: `on_conflict_do_update(constraint='uq_products_sku', ...)`, or when passing the `UniqueConstraint` object itself. `index_elements` suits a plain unique column; `index_where` is added for a partial unique index. The two arguments are mutually exclusive, and SQLAlchemy raises `ValueError` if you pass both or neither.
- What does where= add to on_conflict_do_update()?It renders a WHERE after `DO UPDATE SET`, so a conflicting row that fails the condition is left as it is, effectively DO NOTHING for that row. The importer uses `where=products.c.price_cents != stmt.excluded.price_cents` to skip rewriting unchanged products, which also keeps them out of the RETURNING rows.
- sqlalchemy.insert() has on_conflict_do_update() on every backend.
- on_conflict_do_update() can omit the conflict target, just like DO NOTHING.
- Inside set_, products.c.price_cents means the incoming value of the row.
- MySQL's on_duplicate_key_update() reads the incoming row through stmt.excluded.
- An empty set_ dict turns the upsert into a silent do-nothing.