Diagnostic Queries
Symptoms
A PL/pgSQL SELECT … INTO STRICT expected exactly one row but the query returned several. PostgreSQL raises SQLSTATE P0003 (too_many_rows).
- Only occurs with the
STRICToption in PL/pgSQL. - The query matched multiple rows when one was required.
- Often a missing/non-unique key in the WHERE clause.
What the server log shows
ERROR: query returned more than one row
CONTEXT: PL/pgSQL function get_customer(text) line 5 at SQL statement
Why PostgreSQL raises this — what the manual says
Section 41.5.3 Executing a Command with a Single-Row Result:
“If the STRICT option is specified, the command must return exactly one row or a run-time error will be reported, either NO_DATA_FOUND (no rows) or TOO_MANY_ROWS (more than one row).”
INTO STRICT can assign only one row to its targets. When the query yields more than one, PL/pgSQL cannot choose deterministically and raises P0003.
Common causes
- A WHERE clause that is not actually unique.
- Joining produces duplicate rows.
- Looking up by a non-key column expecting uniqueness.
How to fix it
- Make the predicate unique (filter on a primary/unique key).
- Add
LIMIT 1with an explicitORDER BYif any single row is acceptable. - Drop
STRICTand loop over results if multiple rows are valid.
Related & next steps
Reference: PostgreSQL 18 Section 43.5 “Basic Statements”.
Thanks — noted. This helps keep the database accurate.