Goal This query identifies user-defined routines that execute a standalone INSERT INTO <table> statement and immediately follow it with an UPDATE statement that verifies the existence of the newly inserted row via EXISTS (SELECT ... FROM <same_table>), rather than chaining the operations atomically within a single statement using a data-modifying Common Table Expression (WITH ... AS (INSERT INTO ... RETURNING ...) UPDATE ...). Splitting coupled data modifications into a standalone INSERT followed by an UPDATE ... WHERE EXISTS (...) on the target table introduces both performance overhead and potential logic flaws:

  • Redundant index scan and locking: Instead of passing the newly inserted row's key directly in memory via the RETURNING clause of a CTE, the database is forced to perform an additional index lookup (and often an extra FOR SHARE lock) on the table into which it just inserted the row.

  • Flawed conditional execution: If the INSERT ... SELECT statement inserts zero rows (for example, because a referenced classifier is inactive or an ON CONFLICT DO NOTHING clause is triggered), but a matching row already existed in the table from a prior operation, the subsequent WHERE EXISTS (SELECT 1 FROM <table> ...) still evaluates to TRUE and erroneously updates the parent entity's audit fields (last_modified_by, last_modified_time).

Notes Queries the PostgreSQL system catalogs (pg_proc and pg_namespace) to inspect the decompiled source code (pg_get_functiondef) of user-defined functions and procedures (prokind IN ('f', 'p')). The query uses a case-insensitive regular expression with a backreference (\1) to capture the target table name in an INSERT INTO <table> ...; statement and detect whether the immediately following UPDATE statement performs an EXISTS (SELECT ... FROM <same_table>) subquery against the identical table \1. For better readability in a web browser, < characters are escaped and newline characters are replaced with HTML line break (<br>) tags. Routine parameters are included alongside the schema and routine name to uniquely identify overloaded routines.
Type Problem detection Each row in the result could represent a flaw in the design
Reliability Medium Medium number of false-positive results
License MIT (opens in new tab)
Data Source INFORMATION_SCHEMA+system catalog
SQL Query
WITH routines_src AS (
  SELECT 
    n.nspname AS routine_schema, 
    p.proname AS routine_name, 
    pg_get_function_identity_arguments(p.oid) AS parameters,
    CASE WHEN p.prokind = 'f' THEN 'FUNCTION' ELSE 'PROCEDURE' END AS routine_type,
    CASE WHEN p.prokind <> 'a' THEN pg_get_functiondef(p.oid) ELSE NULL END AS raw_src
  FROM pg_catalog.pg_proc p
  INNER JOIN pg_catalog.pg_namespace n ON p.pronamespace = n.oid
  WHERE p.prokind IN ('f', 'p')
    AND n.nspname NOT IN (
      SELECT schema_name FROM INFORMATION_SCHEMA.schemata
      WHERE schema_name <> 'public' AND schema_owner = 'postgres' AND schema_name IS NOT NULL
    )
)
SELECT 
  routine_schema, 
  routine_name, 
  parameters,
  routine_type,
  regexp_replace(regexp_replace(raw_src, '<', '&lt', 'g'), '[\r\n]', '<br>', 'g') AS routine_src
FROM routines_src
WHERE   
  raw_src ~* '\yINSERT[[:space:]]+INTO[[:space:]]+([[:alnum:]_."]+)[^;]+;[[:space:]]*\yUPDATE\y[^;]+\yEXISTS[[:space:]]*\([[:space:]]*SELECT\y[^;]+\yFROM[[:space:]]+\1\y'
ORDER BY routine_schema, routine_name, parameters;

Fixing Suggestion

Combine the two statements into a single atomic statement using a data-modifying Common Table Expression (WITH clause) with RETURNING. Capture the key of the inserted row in the CTE (e.g., WITH inserted AS (INSERT INTO child_table ... RETURNING parent_id)) and filter the outer UPDATE statement using the CTE result (UPDATE parent_table SET ... WHERE parent_id IN (SELECT parent_id FROM inserted)). This eliminates the redundant table lookup and ensures that the parent table is updated if and only if a new row was actually inserted.

Collections

This query belongs to the following collections:

Find problems automatically

Queries, that results point to problems in the database. Each query in the collection produces an initial assessment. However, a human reviewer has the final say as to whether there is a problem or not .

NameDescription
Find problems automaticallyQueries, that results point to problems in the database. Each query in the collection produces an initial assessment. However, a human reviewer has the final say as to whether there is a problem or not .

Categories

This query is classified under the following categories:

User-defined routines

Queries of this category provide information about the user-defined routines

NameDescription
User-defined routinesQueries of this category provide information about the user-defined routines