SQLSTATE P0002 ERROR Class P0: PL/pgSQL Error

no_data_found query returned no rows — P0002

PostgreSQL error “query returned no rows — P0002” (SQLSTATE P0002): what it means, common causes, and how to fix it.

PG 9.6, 10, 11, 12, 13, 14, 15, 16, 17, 18 Official docs
Last reviewed Jun 2026 Grounded in source

Diagnostic Queries

Symptoms

A PL/pgSQL SELECT … INTO STRICT returned no rows. PostgreSQL raises SQLSTATE P0002 (no_data_found).

  • A STRICT INTO query found zero rows.
  • STRICT requires exactly one row.
  • Common when the lookup key doesn’t match.

What the server log shows

ERROR:  query returned no rows
CONTEXT:  PL/pgSQL function get_user(integer) 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).”

With INTO STRICT, PL/pgSQL requires exactly one result row. When the query returns none, it raises P0002 so the missing-data case is handled explicitly.

Common causes

  • The lookup key matched no rows.
  • Filtering criteria excluded all rows.
  • Expecting a row that was deleted/never inserted.

How to fix it

  1. Handle the case with an EXCEPTION WHEN NO_DATA_FOUND block.
  2. Use non-STRICT INTO and check NOT FOUND if zero rows is valid.
  3. Verify the lookup key exists before the STRICT query.

Related & next steps

Reference: PostgreSQL 18 Section 43.5 “Basic Statements”.

Was this helpful?