skip to content

Why does a SQLAlchemy 2.1 query that joins Customer.payments and filters on CardPayment.card_last4 warn of a cartesian product under joined-table inheritance, and how do you fix it?

level: seniorimportance: should knowfreq 18%

answer

  1. relationship targets the base mapper
  2. subtable added to FROM, unjoined
  3. FROM linter raises an SAWarning
  4. narrow the relationship to a subtype

basics

~10 s

Customer.payments targets Payment, so the join reaches only the payment table and card_payment enters the FROM clause unjoined. Join Customer.payments.of_type(CardPayment) instead; it renders payment JOIN card_payment inside the join.

solid answer

~40 s

In a joined hierarchy the `Payment` mapper's selectable is just `payment`, so `.join(Customer.payments)` joins `customer` to `payment` only. Referencing `CardPayment.card_last4` in `.where()` drags `card_payment` into the FROM list with no ON clause, giving `FROM customer JOIN payment ..., card_payment`, a cartesian product that returns customers who never used that card. SQLAlchemy's FROM linter, on by default, compiles the statement and emits an `SAWarning` about it, but the query still runs. The fix is `.join(Customer.payments.of_type(CardPayment))`, which renders `JOIN (payment JOIN card_payment ON payment.id = card_payment.id)`. To filter several subtypes at once, join `of_type(with_polymorphic(Payment, [...]))` and use its subclass namespaces. Single-table mappings hide the bug because the column already lives on `payment`.

code

python · 65 lines
python
import warnings

from sqlalchemy import ForeignKey, String, create_engine, select
from sqlalchemy.orm import DeclarativeBase, Mapped, Session, mapped_column, relationship


class Base(DeclarativeBase):
    pass


class Customer(Base):
    __tablename__ = "customer"
    id: Mapped[int] = mapped_column(primary_key=True)
    name: Mapped[str]
    payments: Mapped[list["Payment"]] = relationship(back_populates="customer")


class Payment(Base):
    __tablename__ = "payment"
    id: Mapped[int] = mapped_column(primary_key=True)
    customer_id: Mapped[int] = mapped_column(ForeignKey("customer.id"))
    type: Mapped[str] = mapped_column(String(20))
    customer: Mapped[Customer] = relationship(back_populates="payments")
    __mapper_args__ = {"polymorphic_on": "type", "polymorphic_identity": "payment"}


class CardPayment(Payment):
    __tablename__ = "card_payment"
    id: Mapped[int] = mapped_column(ForeignKey("payment.id"), primary_key=True)
    card_last4: Mapped[str] = mapped_column(String(4))
    __mapper_args__ = {"polymorphic_identity": "card"}


class BankTransfer(Payment):
    __tablename__ = "bank_transfer"
    id: Mapped[int] = mapped_column(ForeignKey("payment.id"), primary_key=True)
    iban: Mapped[str] = mapped_column(String(34))
    __mapper_args__ = {"polymorphic_identity": "bank_transfer"}


engine = create_engine("sqlite://")
Base.metadata.create_all(engine)
with Session(engine) as session, session.begin():
    acme = Customer(name="acme", payments=[CardPayment(card_last4="4242")])
    globex = Customer(name="globex", payments=[BankTransfer(iban="GB33BUKB20201555555555")])
    session.add_all([acme, globex])

with Session(engine) as session:
    broken = (
        select(Customer.name)
        .join(Customer.payments)
        .where(CardPayment.card_last4 == "4242")
    )
    with warnings.catch_warnings(record=True) as caught:
        warnings.simplefilter("always")
        print(session.scalars(broken).all())  # ['acme', 'globex']: wrong
    print(caught[0].message)

    fixed = (
        select(Customer.name)
        .join(Customer.payments.of_type(CardPayment))
        .where(CardPayment.card_last4 == "4242")
    )
    print(fixed)
    print(session.scalars(fixed).all())  # ['acme']

go deeper

for a junior

Know that a relationship to a base class joins only the base table in a joined hierarchy, and that of_type() narrows the join to a subclass.

for a middle

Explain why naming a subtable column in WHERE adds an unjoined FROM element, what the FROM linter reports, and what SQL of_type() renders instead.

for a senior

Diagnose the wrong rows from the warning and the SQL log, fix them with of_type or a with_polymorphic target, and make such warnings fail the tests.

for a principal

Set a team rule that criteria on subtype columns always go through of_type, so a later change from single-table to joined storage cannot silently corrupt query results.

## The symptom A joined-table hierarchy maps `Payment` to `payment`, `CardPayment` to `card_payment` and `BankTransfer` to `bank_transfer`, and `Customer.payments` is a one-to-many `relationship()` to `Payment`. Someone writes "customers who paid with the card ending 4242": ```python stmt = ( select(Customer.name) .join(Customer.payments) .where(CardPayment.card_last4 == "4242") ) ``` The query returns customers who never used that card, and the log carries an `SAWarning` that the SELECT "has a cartesian product between FROM element(s)". The rendered SQL shows why: `FROM customer JOIN payment ON customer.id = payment.customer_id, card_payment WHERE card_payment.card_last4 = ?`. The table `card_payment` sits in the FROM list with **no join condition**, so every customer-payment pair is combined with every matching card row. ## Why the join stops at the payment table - `Customer.payments` targets the **`Payment` mapper**, and in a joined hierarchy the base mapper's selectable is just the `payment` table. Joining along the relationship therefore joins `customer` to `payment` and nothing else. - `CardPayment.card_last4` is a column of `card_payment`. Mentioning it in `.where()` makes SQLAlchemy add that table to the FROM clause, because a column must come from somewhere, but nothing in the statement says how it relates to `payment`. - SQLAlchemy does not guess that you meant the card subtype of the relationship. Its **FROM linter**, on by default through `create_engine(enable_from_linting=True)`, notices the disconnected FROM element when the statement compiles and warns. The warning is the only signal. The statement still runs, and the result is plausible-looking and wrong, which is why it tends to surface as a data bug rather than an error. ## Reading the evidence Two artefacts point straight at the cause, and both are worth knowing by sight: - The **warning text** names the disconnected elements: `SELECT statement has a cartesian product between FROM element(s) "card_payment" and FROM element "payment". Apply join condition(s) between each element to resolve.` A subclass table on one side and its base table on the other is the inheritance signature. - The **SQL log** (engine `echo` or the engine logger) shows the subtable after a **comma** in the FROM clause rather than inside a `JOIN ... ON`. A comma-separated table in ORM-generated SQL usually means a missing join. Row counts give a third hint: the broken query returns every customer-payment pair once for each matching card row, so results grow with unrelated data. ## The fix: PropComparator.of_type() `of_type()` narrows a relationship to one subtype for the duration of a join: ```python stmt = ( select(Customer.name) .join(Customer.payments.of_type(CardPayment)) .where(CardPayment.card_last4 == "4242") ) ``` The SQL becomes `FROM customer JOIN (payment JOIN card_payment ON payment.id = card_payment.id) ON customer.id = payment.customer_id`. Both tables are joined, the criteria apply to the right rows, and because the target is the concrete `CardPayment` mapping the inner join is a plain JOIN, which the documentation notes is generally kinder to the planner than a LEFT OUTER JOIN. ## Variations of the same rule 1. **Criteria across several subtypes.** Build `poly = with_polymorphic(Payment, [CardPayment, BankTransfer])` and join `Customer.payments.of_type(poly)`; then `or_(poly.CardPayment.card_last4 == "4242", poly.BankTransfer.iban == ...)` works in one statement, over LEFT OUTER JOINs. 2. **Loader options.** `selectinload(Customer.payments.of_type(CardPayment))` or `.of_type(poly)` controls what an eager load fetches in the same way. 3. **No relationship at all.** `select(Payment).where(CardPayment.card_last4 == "4242")` has the same defect: only `payment` is in the FROM clause. Select `CardPayment` directly, or select from a `with_polymorphic()` entity. 4. **Mapper-level loading.** If the subclass sets `polymorphic_load="inline"`, base-class statements already include its table and subclass columns can be referenced directly. That is a mapping decision, not a fix to reach for in one query. ## Why a single-table mapping hides the bug | | Single-table | Joined-table | |---|---|---| | Where `card_last4` lives | the `payment` table | the `card_payment` table | | `.join(Customer.payments).where(CardPayment.card_last4 == ...)` | correct: column already in FROM, ORM adds `payment.type IN (...)` | cartesian product with an `SAWarning` | | `.join(Customer.payments.of_type(CardPayment))` | `JOIN payment ON ... AND payment.type IN (...)` | `JOIN (payment JOIN card_payment ...)` | A codebase that started single-table and moved a subtype to its own table can therefore break queries that were correct the day before. Writing `of_type()` whenever criteria name a subtype makes the query independent of how the subtype is stored. ## Review checklist - Treat every cartesian-product `SAWarning` as a bug; consider turning SQLAlchemy warnings into errors in the test suite. - Any `.where()` naming a subclass attribute after a relationship join should have `of_type()` on that join. - Prefer joining the concrete subclass over a `with_polymorphic()` target when only one subtype is filtered.

  • How would you stop this class of bug from reaching production?
    Make the warning fatal where it matters: run the test suite with SQLAlchemy warnings turned into errors (a warnings filter on `SAWarning`), keep `enable_from_linting` at its default `True`, and add a review rule that any criteria naming a subclass attribute after a relationship join needs `of_type()` on that join.
  • When would you join of_type(with_polymorphic(...)) rather than of_type(CardPayment)?
    When one statement must apply criteria to more than one subtype, for example cards ending 4242 or transfers from one IBAN. The polymorphic entity LEFT OUTER JOINs every listed subtable and exposes `.CardPayment` and `.BankTransfer` namespaces. For one subtype, joining the subclass directly gives an inner join, which the planner usually handles better.

  • SQLAlchemy infers the subtype from the WHERE clause and adds the JOIN itself.
  • A cartesian product warning is cosmetic as long as the query returns rows.
  • selectin_polymorphic() on the query fixes a filter on subtype columns.
  • Switching the join to isouter=True removes the cartesian product.
  • The query fails the same way in a single-table hierarchy.