How to Fix Postgres Error 21000 Cardinality Violation

Published
Length
4 min read

Luis Felipe Dias

All posts

A postgres error 21000 cardinality violation occurs when a scalar expression or subquery returns more than one row where the database engine expects a single value. You resolve it by constraining the subquery to return one row. Rewriting the join logic, or removing duplicate source records. Running an update or merge task. In the official PostgreSQL specs. SQLSTATE 21000 maps to the internal macro ERRCODE_CARDINALITY_VIOLATION. Unlike syntax mistakes, this error often passes staging tests and a

Your coding agents run with your access.

Claude Code reaches prod with a developer's credentials, and approval prompts get clicked through. hoop.dev checks every query, masks sensitive data, and holds risky changes for a human.

A postgres error 21000 cardinality violation occurs when a scalar expression or subquery returns more than one row where the database engine expects a single value. You resolve it by constraining the subquery to return one row. Rewriting the join logic, or removing duplicate source records. Running an update or merge task.

In the official PostgreSQL specs. SQLSTATE 21000 maps to the internal macro ERRCODE_CARDINALITY_VIOLATION. Unlike syntax mistakes, this error often passes staging tests and appears in production only data volume grows or unexpected duplicate rows enter a table understanding why the database engine rejects the query helps teams. Fix the problem without risking data corruption.

Root causes of a postgres error 21000 cardinality violation

PostgreSQL enforces strict rules whenever a query context. Requires a scalar value if you place a subquery inside a column list. An equality filter, or a variable assignment that subquery can return at most one row. The moment the underlying tables contain two or more matching rows for that subquery. The engine halts execution and raises SQLSTATE 21000.

A second major trigger happens during batch data changes. When an update statement or a merge command joins a target table against a source dataset. Multiple source rows might match the same target row because PostgreSQL cannot guess which source row should win. It aborts the transaction with a cardinality violation rather than applying arbitrary updates.

Stored functions and procedures also trigger this failure. Assigning query results into scalar variables with strict single-row checks enabled if a lookup table develops duplicate keys due to a missing unique limit. Routine app calls suddenly fail across the cluster.

How to diagnose and fix the failure in production

To fix a cardinality violation in production start by isolating the exact subquery or source. Join that produced multiple rows. Engineers often need to inspect production tables to see which duplicate keys caused the failure. Never grant broad write grants or superuser roles to fix data anomalies.

Instead, follow least-rights practices from the PostgreSQL docs. Set up group roles to manage rights. Many users need diagnostic visibility, and grant users membership in a read-only group role remember that the SELECT rights allows reading from exact columns of a table or view. You can expose join keys to developers without exposing sensitive payload columns.

End-to-End Encryption + Policy Violation Detection: architecture patterns and best practices

Continue reading? Get the full guide.

Free. No spam. Unsubscribe anytime.

Also review default database roles during your investigation. The special role name PUBLIC grants rights to every role on the system including default execute rights on functions and procedures in PostgreSQL 15 and later, the default config no longer lets every user create objects in the public schema. Admins on upgraded databases revoke that ability from PUBLIC to keep fixing systems clean.

Once you identify the duplicate rows using scoped read access. Choose the right logical fix if any matching row is acceptable. Add an explicit aggregation function or a fixed row. Limit with ordering to the subquery if the subquery filters a parent query replace the scalar equality check with an existence check or a set membership operator for batch updates and merges, deduplicate the source dataset in a common table expression. Joining it to the target table add a unique limit to prevent future duplicates.

Preventing recurring cardinality failures in application queries

Long-term prevention requires aligning database schema limits with app query assumptions. Every scalar subquery relies on the assumption that its filter condition targets a unique key if the filtered column lacks a unique index or primary key limit. Data drift will eventually break the query.

Audit your codebase for scalar subqueries inside select. Lists and replace them with explicit left joins or lateral joins that define clear ordering and row limits. When testing data migrations or bulk imports. Test against realistic data distributions that include one-to-many relationships. Enforcing uniqueness at the schema layer ensures that invalid duplicate records fail during insertion. Breaking read and update queries later.

Check every Postgres query on the wire

Database roles and network rules decide who can open a session. They do not read what each SQL statement does after login. With hoop.dev, you run an open-source proxy, a sidecar for your Postgres, inline in the Postgres wire protocol. On every query an AI agent or engineer runs against production, hoop.dev decides to pass, mask, block, or hold it for human review. Your apps and agents keep their login details and change only the host and port in the connection string their tool uses.

Before a query runs, hoop.dev guardrails refuse bad deletes or drops with a real Postgres error, or hold risky queries for approval. On the way back, hoop.dev data masking rewrites sensitive values in returned rows in memory, and every verdict goes to the audit trail. Furthermore, hoop.dev holds SOC 2 Type II, is MIT licensed, and generates evidence for HIPAA, GDPR, and PCI DSS. See the code on GitHub.

Frequently asked questions

What does SQLSTATE 21000 mean in PostgreSQL?

SQLSTATE 21000 is the standard code for ERRCODE_CARDINALITY_VIOLATION. It means a query or data change statement returned multiple rows in A context where PostgreSQL requires zero or one row.

Why did my update query fail with a cardinality violation?

An update or merge statement fails with this error. The joined source table matches a single target. Row more than once. You must group or deduplicate the source rows so each target row. Receives only one update value within the same command.

How can developers inspect duplicate rows without full table access?

Admins can grant the SELECT rights on exact ID columns. The entire table assigning developers to a dedicated group role lets them. Query key distributions and find duplicates. Keeping sensitive columns restricted.

The query runs. The emails stay hidden.