PG
PRO
P0003ERRORTier 2 — Caution✅ HIGH confidence

too_many_rows

Category: PL/pgSQL ErrorVersions: All PostgreSQL versions with PL/pgSQL

What this means

A SELECT INTO STRICT statement in PL/pgSQL returned more than one row, violating the expectation that exactly one row would be returned.

Why it happens

  1. 1SELECT INTO STRICT query matched multiple rows when only one was expected
  2. 2Missing or insufficiently selective WHERE clause in SELECT INTO STRICT
  3. 3Data grew to include duplicates since the function was written, now multiple rows match
  4. 4Unique constraint missing on the queried column

How to reproduce

PL/pgSQL function using SELECT INTO STRICT where the query can return multiple rows

trigger — this will ERROR
CREATE OR REPLACE FUNCTION get_user_by_name(uname text) RETURNS int AS $
DECLARE
  uid int;
BEGIN
  SELECT id INTO STRICT uid FROM users WHERE name = uname;
  RETURN uid;
END;
$ LANGUAGE plpgsql;

-- If multiple users have the same name:
SELECT get_user_by_name('Alice');
ERROR: P0003: query returned more than one row

Fix 1: Add LIMIT 1 if exactly one row is acceptable

Any matching row is sufficient

fix
SELECT id INTO uid FROM users WHERE name = uname LIMIT 1;

Why this works

Removes the STRICT constraint and limits to one row; eliminates the too_many_rows error

Fix 2: Handle too_many_rows in an EXCEPTION block

Multiple rows indicate a data integrity problem

fix
BEGIN
  SELECT id INTO STRICT uid FROM users WHERE name = uname;
EXCEPTION WHEN too_many_rows THEN
  RAISE EXCEPTION 'Duplicate user name found: %', uname;
END;

Why this works

Surfaces the ambiguity as an application error with a clear message

What not to do

Do not silently take the first row with LIMIT 1 if duplicate rows indicate a data corruption problem

Why it's wrong: Hiding the ambiguity can mask data integrity issues

Sources

📚 Official docs: https://www.postgresql.org/docs/current/plpgsql-statements.html#PLPGSQL-STATEMENTS-SQL-ONEROW

🔧 Source ref: https://www.postgresql.org/docs/current/errcodes-appendix.html

Confidence assessment

✅ HIGH confidence

Well-documented PL/pgSQL error; frequently encountered in production stored procedures.

See also

📄 Reference pages

PL/pgSQL SELECT INTO STRICT
⚙️ This error reference was generated with AI assistance and reviewed for accuracy. Examples are provided to illustrate common scenarios and may not cover every case. Always test fixes in a development environment before applying to production. Spotted an error? Suggest a correction →