python data_error ai_generated true

sqlalchemy.exc.MultipleResultsFound: Multiple rows were found for one()

ID: python/sqlalchemy-query-too-many-rows

Also available as: JSON · Markdown · 中文
80%Fix Rate
86%Confidence
0Evidence
2025-09-10First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.x active

Root Cause

Using the one() method on a query that returns more than one row, which expects exactly one.

generic

中文

对返回多行的查询使用 one() 方法,而该方法期望只返回一行。

Workarounds

  1. 95% success Use one_or_none() to handle zero or one result
    user = session.query(User).filter_by(id=user_id).one_or_none()
    if user is None:
        # Handle not found
        pass
  2. 90% success Use scalar() for single column queries
    count = session.query(func.count(User.id)).scalar()

Dead Ends

Common approaches that don't work:

  1. Using first() instead without checking 60% fail

    first() returns None if no rows, masking potential logic errors.

  2. Ignoring the error and assuming one row 100% fail

    The error will still occur.