PostgreSQL P0002 No Data Found: Fix It Fast
In this article
The PostgreSQL error P0002 (no_data_found) means a PL/pgSQL block executed a statement that was expected to return a row, but returned none. The fix is to stop assuming a row exists: use SELECT ... INTO with a check on the FOUND variable, or switch to a query that returns a value even when the row is missing, such as a subquery with COALESCE or an aggregate. In most cases the error comes from a SELECT INTO or a STRICT query inside a function, procedure, or DO block. The steps below show how to find the failing statement, confirm why no row came back, and rewrite it so the error cannot occur.
What You'll Need
- Access to the PostgreSQL server with a role that can read the failing function or procedure definition (or the application logs that show the full error).
- A SQL client such as psql, pgAdmin, or DBeaver.
- The name of the function or procedure that raised the error, or the text of the
DOblock, if you have it. - Permission to run
CREATE OR REPLACE FUNCTIONorCREATE OR REPLACE PROCEDUREif the fix requires editing code.
Step-by-Step
Read the full error message. P0002 usually appears with a line like
ERROR: query returned no rowsand aCONTEXTline naming the function and the statement. In psql the context is printed automatically; in an application, check the server log or enablelog_min_error_statementso the failing statement is recorded. The context line is what tells you whichSELECT INTOorSTRICTquery failed.Locate the code. Use
\df+ schema.function_namein psql, or querypg_procwithSELECT prosrc FROM pg_proc WHERE proname = 'function_name';to see the body. If the error came from an anonymous block, you already have the text. Look for any of these patterns:SELECT ... INTO variable FROM ...,SELECT ... INTO STRICT variable, anUPDATE ... RETURNING ... INTO, or a query with theSTRICTkeyword.Reproduce the query outside the function. Copy the failing statement and run it with the same parameters, replacing the
INTOtarget with a plainSELECT. For example, if the function runsSELECT name INTO v_name FROM users WHERE id = p_id;, runSELECT name FROM users WHERE id = 42;using the actual parameter value from the error context. If it returns zero rows, you have confirmed the cause: the row the code expected does not exist.Decide what the code should do when there is no row. There are three common correct behaviours: treat a missing row as an error and raise a clearer exception, treat it as normal and continue with a default value, or return a result that tells the caller nothing was found. Choose one before editing, because the fix differs for each.
Fix option A: check
FOUNDafter a non-strictSELECT INTO. RemoveSTRICTif it is present, then test the special variableFOUNDimmediately after the statement:
This keeps the error but with your own message, or you can replace theSELECT name INTO v_name FROM users WHERE id = p_id; IF NOT FOUND THEN RAISE EXCEPTION 'User % not found', p_id USING ERRCODE = 'P0002'; END IF;RAISEwith a default assignment such asv_name := 'unknown';and continue.Fix option B: make the query always return a row. Wrap the lookup in a scalar subquery with
COALESCE, or use an aggregate that returns one row even over an empty set:
A plainSELECT COALESCE((SELECT name FROM users WHERE id = p_id), 'unknown') INTO v_name;SELECT count(*)orSELECT max(column)also always returns exactly one row, so it never triggers P0002. Use this when a missing row is a normal case, not an error.Fix option C: use
RETURN QUERYfor set-returning functions. If the function returns a set and you usedSELECT INTOby mistake, replace it withRETURN QUERY SELECT .... A set-returning function that finds no rows should return an empty set, not raise P0002.Apply the change. Use
CREATE OR REPLACE FUNCTION schema.name(args) RETURNS ... AS $$ ... $$ LANGUAGE plpgsql;for functions, orCREATE OR REPLACE PROCEDUREfor procedures. Keep the original argument types and return type identical, otherwise PostgreSQL creates a new overload instead of replacing the old one. Test in a transaction first if the change is risky:BEGIN; CREATE OR REPLACE ...; -- run tests; ROLLBACK;.Re-run the failing case. Call the function with the same parameters that produced the error and confirm it now returns the expected result or raises your clearer message. Also test the case where the row does exist, so you have not broken the normal path.
Common Mistakes
- Adding
STRICTto silence a warning.STRICTmakes a zero-row result an error, so it does the opposite of fixing P0002. Use it only when a missing row truly is a bug. - Checking
FOUNDtoo late.FOUNDis set by the most recent SQL statement, so any query between theSELECT INTOand theIF NOT FOUNDcheck overwrites it. Test it immediately. - Assuming
SELECT INTOreturns NULL. WithoutSTRICT, a zero-rowSELECT INTOleaves the variable unchanged (often NULL), which can hide the problem until later. WithSTRICT, it raises P0002 immediately. Know which behaviour your code relies on. - Replacing a function with different argument types.
CREATE OR REPLACE FUNCTIONonly replaces a function with the same signature; a changed type creates an overload and the old code keeps running. - Looking only at the application code. P0002 can come from a trigger, a view, or a function called by another function. The
CONTEXTline in the error names the actual source.
Tips
- Raise P0002 deliberately with
RAISE EXCEPTION ... USING ERRCODE = 'P0002';when you want callers to handle a missing row consistently. - Prefer
COALESCEwith a scalar subquery overSELECT INTOwhen a missing row is expected and you just need a default. - Keep functions small and test them with both existing and missing rows; P0002 is almost always a data assumption, not a syntax problem.
- Turn on
log_min_error_statement = errorinpostgresql.confso the failing statement is logged with the error, which shortens diagnosis.
Troubleshooting
If the error persists after editing the function, confirm the application is calling the version you changed: check SELECT proname, pg_get_function_identity_arguments(oid) FROM pg_proc WHERE proname = 'name'; and look for duplicate overloads. If the error comes from a trigger, the CONTEXT names the trigger function, so edit that function instead. If you cannot reproduce the error manually, the parameter values in production differ from your test values; capture them from the application log or add temporary RAISE NOTICE lines with the parameter values, then remove them. If the error appears only under concurrency, a row may be deleted between the check and the use; wrap the read and the dependent write in a single statement or use SELECT ... FOR UPDATE where appropriate. If you lack permission to replace the function, ask the owner or a superuser; do not attempt to edit system catalogs directly.
Frequently Asked Questions
What does PostgreSQL error P0002 mean?
P0002 is the SQLSTATE for no_data_found. In PL/pgSQL it is raised when a SELECT INTO with STRICT, or an equivalent strict query, returns zero rows.
Does a normal SELECT INTO raise P0002?
No. Without STRICT, a zero-row SELECT INTO leaves the target variable unchanged and does not raise an error. Only the strict form raises P0002.
How do I return a default when no row exists?
Use SELECT COALESCE((SELECT column FROM table WHERE ...), default_value) INTO variable; or check FOUND after a non-strict SELECT INTO and assign the default yourself.
Can P0002 come from a trigger?
Yes. Any PL/pgSQL code, including trigger functions, can raise it. The CONTEXT line in the error identifies the function and statement responsible.
Is P0002 the same as a unique violation?
No. A unique violation is SQLSTATE 23505. P0002 is specifically about a query returning no rows where one was required.
How do I raise P0002 on purpose?
Use RAISE EXCEPTION 'message' USING ERRCODE = 'P0002'; inside a PL/pgSQL block so callers can handle a missing row in a standard way.