python data_error ai_generated true

sqlalchemy.exc.MultipleResultsFound: Multiple rows were found when exactly one was required

ID: python/sqlalchemy-query-multiple-rows

Also available as: JSON · Markdown · 中文
80%Fix Rate
88%Confidence
0Evidence
2024-02-14First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.4.x active
2.0.x active

Root Cause

Using .one() on a query that returns more than one row.

generic

中文

对返回多行的查询使用了 .one()。

Workarounds

  1. 90% success
    Use .scalar_one() if you expect exactly one row, or .one_or_none() if zero is acceptable.
  2. 95% success
    Add filters to narrow down the result: query.filter(User.id == some_id).one()

Dead Ends

Common approaches that don't work:

  1. 60% fail

    Silently ignores extra rows, possibly hiding data issues.

  2. 70% fail

    Doesn't solve the root cause; may still return the wrong row.