DBAtlas · Database operations atlas

21000: cardinality_violation

PostgreSQL

What does it mean?

More than one row was returned where a single row was expected. A scalar subquery returned multiple rows, or MERGE/ON CONFLICT DO UPDATE tried to affect the same target row a second time. Belongs to Class 21.

Why does it happen?

A subquery used in the SELECT list or in the form WHERE = (subquery) returning multiple rows; the same conflict key being proposed more than once in a single INSERT ... ON CONFLICT DO UPDATE ('cannot affect row a second time'); or multiple source rows matching one target row in MERGE. UPDATE ... FROM does not raise an error on multiple matches; the target row is updated from only one of the source rows, unpredictably.

How to fix it

Make sure the subquery returns a single row: add LIMIT 1, use an aggregate (MAX/MIN), or supply a condition that makes the match unique. In MERGE and ON CONFLICT patterns, deduplicate the source side with DISTINCT ON/aggregate; do the same for UPDATE ... FROM to avoid silently wrong results. To find unexpected multiple matches, run the subquery on its own and check the row count.

Open in DBAtlas →

More from this engine