Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

PostgreSQL P0002 No Data Found: Fix It Fast

· 6 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

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 DO block, if you have it.
  • Permission to run CREATE OR REPLACE FUNCTION or CREATE OR REPLACE PROCEDURE if the fix requires editing code.

Step-by-Step

  1. Read the full error message. P0002 usually appears with a line like ERROR: query returned no rows and a CONTEXT line naming the function and the statement. In psql the context is printed automatically; in an application, check the server log or enable log_min_error_statement so the failing statement is recorded. The context line is what tells you which SELECT INTO or STRICT query failed.

  2. Locate the code. Use \df+ schema.function_name in psql, or query pg_proc with SELECT 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, an UPDATE ... RETURNING ... INTO, or a query with the STRICT keyword.

  3. Reproduce the query outside the function. Copy the failing statement and run it with the same parameters, replacing the INTO target with a plain SELECT. For example, if the function runs SELECT name INTO v_name FROM users WHERE id = p_id;, run SELECT 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.

  4. 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.

  5. Fix option A: check FOUND after a non-strict SELECT INTO. Remove STRICT if it is present, then test the special variable FOUND immediately after the statement:

    SELECT 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;
    This keeps the error but with your own message, or you can replace the RAISE with a default assignment such as v_name := 'unknown'; and continue.

  6. 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:

    SELECT COALESCE((SELECT name FROM users WHERE id = p_id), 'unknown') INTO v_name;
    A plain SELECT count(*) or SELECT 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.

  7. Fix option C: use RETURN QUERY for set-returning functions. If the function returns a set and you used SELECT INTO by mistake, replace it with RETURN QUERY SELECT .... A set-returning function that finds no rows should return an empty set, not raise P0002.

  8. Apply the change. Use CREATE OR REPLACE FUNCTION schema.name(args) RETURNS ... AS $$ ... $$ LANGUAGE plpgsql; for functions, or CREATE OR REPLACE PROCEDURE for 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;.

  9. 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 STRICT to silence a warning. STRICT makes 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 FOUND too late. FOUND is set by the most recent SQL statement, so any query between the SELECT INTO and the IF NOT FOUND check overwrites it. Test it immediately.
  • Assuming SELECT INTO returns NULL. Without STRICT, a zero-row SELECT INTO leaves the variable unchanged (often NULL), which can hide the problem until later. With STRICT, it raises P0002 immediately. Know which behaviour your code relies on.
  • Replacing a function with different argument types. CREATE OR REPLACE FUNCTION only 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 CONTEXT line 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 COALESCE with a scalar subquery over SELECT INTO when 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 = error in postgresql.conf so 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.