P0002
PostgreSQLERRORNotablePL/pgSQL ErrorHIGH confidence

no_data_found

What this means

A SELECT INTO or FETCH statement inside a PL/pgSQL function returned no rows, and the function was not written to handle that case gracefully.

Why it happens
  1. 1SELECT INTO in PL/pgSQL returned zero rows and STRICT mode is used, or explicit check raises exception
  2. 2FETCH on a cursor that has been exhausted
  3. 3Function expected exactly one row from a query but the table is empty or the WHERE clause matched nothing
How to reproduce

PL/pgSQL function using SELECT INTO STRICT or explicit NOT FOUND check

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

SELECT get_user(99999);  -- user 99999 does not exist

expected output

ERROR:  P0002: query returned no rows

Fix 1

Handle NOT FOUND in an EXCEPTION block

WHEN Zero rows is a valid expected outcome

Handle NOT FOUND in an EXCEPTION block
BEGIN
  SELECT name INTO STRICT uname FROM users WHERE id = uid;
EXCEPTION WHEN no_data_found THEN
  RETURN NULL;  -- or a default value
END;

Why this works

Catches P0002 and returns a sensible default instead of propagating the error

Fix 2

Use SELECT INTO without STRICT and check FOUND

WHEN Zero rows is acceptable and you want to handle it inline

Use SELECT INTO without STRICT and check FOUND
SELECT name INTO uname FROM users WHERE id = uid;
IF NOT FOUND THEN
  RETURN NULL;
END IF;

Why this works

Without STRICT, SELECT INTO does not raise P0002; use the FOUND variable instead

What not to do

Do not use SELECT INTO STRICT for queries that may legitimately return no rows without handling no_data_found

Will raise an unhandled exception on empty results

Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev

← All PostgreSQL errors