Smart Systems for Home

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

PostgreSQL Error 38002: Fix Modifying SQL Data Not Permitted

· 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

PostgreSQL error 38002 occurs when a function or trigger attempts to modify SQL data in a context where it is explicitly forbidden—typically inside a read-only function, a view, or when running under a role with insufficient privileges. This is not a connection or syntax error; it’s a security and transactional integrity safeguard. To resolve it, you must identify where the modification is being attempted and either restructure the function to avoid writes, adjust permissions, or change the execution context. The fix requires understanding PostgreSQL’s function volatility categories and role-based access controls.

What You'll Need

  • Access to the PostgreSQL server with sufficient privileges (superuser or owner of the affected function/view)
  • Ability to query system catalogs like pg_proc, pg_views, or pg_roles
  • Access to the application or SQL script that triggers the error
  • Basic familiarity with PostgreSQL function definitions (CREATE FUNCTION syntax)

Step-by-Step

  1. Identify the exact SQL statement or function causing the error by checking your application logs or PostgreSQL server logs. Look for the function name or query that precedes the 38002 error. Example: "ERROR: 38002: modifying SQL data not permitted in function my_calc_function".
  2. Connect to your PostgreSQL database using a client like psql, pgAdmin, or DBeaver with a superuser or database owner account. Use the command: psql -U username -d database_name.
  3. Check if the function is declared as IMMUTABLE or STABLE. Run: SELECT proname, provolatile FROM pg_proc WHERE proname = 'my_calc_function';. If provolatile is 'i' (immutable) or 's' (stable), it cannot modify data. Only functions marked 'v' (volatile) are allowed to perform writes, and even then, only if called from a writable context.
  4. Locate the function definition using: \df+ my_calc_function in psql or query pg_proc with pg_get_functiondef(). If the function contains INSERT, UPDATE, DELETE, or SELECT FOR UPDATE statements, it is attempting to modify data.
  5. Verify the calling context. If the function is called from a view, materialized view, or a SELECT statement in a read-only transaction (like a replication standby), modifications are blocked. Check if the function is used in a view by querying: SELECT viewname, definition FROM pg_views WHERE definition ILIKE '%my_calc_function%';.
  6. If the function must modify data, change its volatility from STABLE or IMMUTABLE to VOLATILE. Use: ALTER FUNCTION my_calc_function() VOLATILE;. This tells PostgreSQL the function may have side effects.
  7. Ensure the role executing the function has the necessary privileges. Run: SELECT rolname, rolcanlogin, rolsuper FROM pg_roles WHERE rolname = 'current_user';. If the user lacks INSERT/UPDATE/DELETE permissions on the target table, grant them: GRANT UPDATE ON TABLE target_table TO username;.
  8. If the function is used in a view, consider replacing the view with a materialized view or a table function. Views cannot support data-modifying operations. Instead, create a table function that returns the desired result set and handles writes separately.
  9. Test the fix by calling the function directly in a writable transaction: SELECT my_calc_function();. If it runs without error, the issue is resolved. If not, check for triggers on the target table that may be firing and also violating write rules.
  10. Update any application code that relies on the function to handle the new volatility or permission requirements. Restart application services if they cache SQL plans or function metadata.

Common Mistakes

  • Assuming changing the function to VOLATILE alone fixes everything—permissions on target tables must also be granted.
  • Trying to modify data inside an IMMUTABLE function, which is logically impossible and violates PostgreSQL’s optimization assumptions.
  • Using a function in a SELECT clause of a view that contains an UPDATE statement, which PostgreSQL explicitly blocks to prevent side effects during read operations.
  • Granting excessive privileges (like ALL on a schema) instead of fine-grained permissions on specific tables, creating security risks.
  • Ignoring replication or standby databases: functions that modify data cannot run on read-only replicas, even if correctly configured on the primary.

Tips

  • Use COMMENT ON FUNCTION to document why a function is VOLATILE and what data it modifies—this helps future maintainers avoid reverting volatility settings.
  • For complex logic that requires writes, prefer stored procedures (CREATE PROCEDURE) over functions. Procedures are designed for side effects and are not restricted by the same read-only contexts.
  • Use SET LOCAL transaction_read_only = off; inside a function only if you’re certain the transaction context allows it—but this rarely works in views or triggers.
  • Test function behavior in a development environment that mirrors production, including replication and read-only configurations.
  • Always wrap data-modifying functions in a transaction block (BEGIN; ... COMMIT;) when testing to avoid partial changes.
  • Use pg_stat_activity to monitor active queries and identify which session triggered the error, especially in multi-user systems.

Troubleshooting

If the error persists after following the steps above, begin with the simplest checks. First, restart the PostgreSQL service to clear any cached function plans. Then, recheck the function’s volatility and permissions using the exact names and case-sensitive identifiers. If the function is called from a trigger, verify the trigger is not firing during a read-only operation (e.g., on a standby). Check if the database is in recovery mode: SELECT pg_is_in_recovery();—if true, no modifications are allowed at all. If the function is part of an extension or third-party schema, review its documentation for known limitations. If you’re using a connection pooler like pgBouncer, ensure it’s not in transaction mode that restricts write functions. If all else fails, create a new function with the same logic but a different name, test it in isolation, then replace the old one. Never drop functions without backup; always backup the function definition with pg_dump -t function_name before modifying it.

Frequently Asked Questions

Can I use UPDATE inside a PostgreSQL function called from a SELECT?

No. PostgreSQL blocks data modifications in functions called from SELECT statements to ensure query predictability. Use a separate procedure or application logic instead.

Why does my function work in psql but not in my app?

Your app may be connecting under a different user role with fewer permissions, or it might be using a read-only connection pool. Check the app’s database connection string and user privileges.

Is there a way to bypass the 38002 error without changing code?

No. The error is intentional for data integrity. Workarounds like changing transaction settings or using dynamic SQL are unreliable and often violate security policies.

Can a materialized view cause this error?

Materialized views themselves don’t cause it, but if you refresh them using a function that modifies data, and the refresh happens in a read-only context, it will fail. Use a scheduled job or trigger to refresh instead.

Do I need superuser privileges to fix this error?

No. You only need ownership of the function or table, or the ALTER FUNCTION and GRANT permissions. Superuser access helps but isn’t required if you have the correct object ownership.

What’s the difference between STABLE and VOLATILE functions?

STABLE functions return the same result within a single transaction and cannot modify data. VOLATILE functions can return different results each time and are allowed to modify data. Use VOLATILE only when side effects are intentional and necessary.