Goal This query identifies user-defined SQL and PL/pgSQL routines (functions, procedures, and trigger functions) that execute a SELECT or PERFORM query with a row-level locking clause (FOR UPDATE, FOR NO KEY UPDATE, FOR SHARE, or FOR KEY SHARE) capable of locking multiple rows (or using LIMIT / FETCH FIRST ... ROWS), but omit an ORDER BY clause.

When a query locks multiple rows without a deterministic ORDER BY clause, PostgreSQL acquires row locks in the order tuples are visited by the execution plan (such as physical heap order or index scan order). Because tuple positions and access paths can vary across concurrent transactions, two transactions locking overlapping sets of rows can acquire locks in opposite orders, resulting in a deadlock. Although FOR SHARE locks are mutually compatible with other FOR SHARE locks, they conflict with write locks (UPDATE, DELETE, FOR [NO KEY] UPDATE); therefore, a multi-row FOR SHARE query can deadlock with a concurrent transaction that modifies the same rows unless both transactions acquire locks in a consistent order (e.g., ascending primary key order). Furthermore, using LIMIT or FETCH FIRST/NEXT with a locking clause without ORDER BY locks an arbitrary subset of rows. Queries that lock at most a single row (such as equality lookups on a PRIMARY KEY or UNIQUE index, or EXISTS (...) subqueries) cannot deadlock due to intra-query row ordering and are excluded.
Notes Refers to the column pg_proc.prokind and thus works starting from PostgreSQL 11. The query inspects the definitions (pg_get_functiondef) of user-defined functions, procedures, and trigger functions (prokind IN ('f', 'p')), strips SQL comments, and uses regexp_matches to extract every statement-level or cursor-loop (FOR ... IN SELECT ... LOOP) SELECT or PERFORM query that specifies FOR [NO KEY] UPDATE or FOR [KEY] SHARE without an outer ORDER BY clause. Parenthesized subqueries such as EXISTS (SELECT ... FOR SHARE) and scalar subqueries are excluded because they stop after or permit at most one row.

A locking query without ORDER BY is flagged if it can lock multiple rows or operates non-deterministically under any of three conditions:

  • The query lacks a WHERE clause entirely (locking all rows in the target table).

  • The query contains multi-row or range predicates (IN (...), = ANY (...), OR, BETWEEN, inequality operators <, >, <=, >=, <>, !=, pattern operators LIKE, ILIKE, ~, IS [NOT] NULL) or a row-limiting clause (LIMIT or FETCH FIRST/NEXT).

  • The WHERE clause uses equality (=), but does not constrain all key columns of any non-partial PRIMARY KEY or UNIQUE index on the target table in pg_index (supporting both regular column indexes via indkey and expression unique indexes via pg_depend).



In the returned routine source code, < characters are escaped (&lt;), newline characters are replaced with HTML line break (<br>) tags, and the locking keywords (FOR [NO KEY] UPDATE / FOR [KEY] SHARE) are highlighted in bold (<b>).
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_base AS (
    SELECT 
        p.oid AS routine_oid,
        n.nspname AS routine_schema, 
        p.proname AS routine_name, 
        CASE 
            WHEN p.prokind IN ('f', 'p') THEN pg_get_function_identity_arguments(p.oid) 
        END AS parameters,
        CASE 
            WHEN pt.typname = 'trigger' THEN 'TRIGGER FUNCTION'
            WHEN p.prokind = 'f' THEN 'FUNCTION'
            WHEN p.prokind = 'p' THEN 'PROCEDURE'
        END AS routine_type,
        CASE 
            WHEN p.prokind IN ('f', 'p') 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
    LEFT JOIN pg_catalog.pg_type pt ON pt.oid = p.prorettype
    WHERE p.prokind IN ('f', 'p')
      AND p.proname NOT IN (
          'f_assume_you_must_use_files', 
          'f_check_format_comma_separated_list', 
          'f_check_password', 
          'f_default_value_with_no_match'
      )
      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
      )
      AND NOT EXISTS (
          SELECT 1
          FROM pg_catalog.pg_depend d 
          INNER JOIN pg_catalog.pg_extension e ON d.refobjid = e.oid
          WHERE d.objid = p.oid
      )
),
routines_cleaned AS (
    SELECT 
        r.*,

        regexp_replace(r.raw_src, '(--[^\n\r]*)|(/\*[\w\W]*?\*/)', ' ', 'g') AS clean_src
    FROM routines_base r
    WHERE r.raw_src ~* '\yFOR[[:space:]]+(?:(?:NO[[:space:]]+)?KEY[[:space:]]+)?(?:UPDATE|SHARE)\y'
)
SELECT 
    r.routine_schema,
    r.routine_name,
    r.parameters,
    r.routine_type,
    regexp_replace(
        regexp_replace(
            regexp_replace(r.raw_src, '<', '&lt;', 'g'),
            '[\r\n]', '<br>', 'g'
        ),
        '(FOR[[:space:]]+(?:(?:NO[[:space:]]+)?KEY[[:space:]]+)?(?:UPDATE|SHARE))', '<b>\1</b>', 'gi'
    ) AS routine_src
FROM routines_cleaned r
WHERE EXISTS (
    SELECT 1

    FROM regexp_matches(
        r.clean_src,
        '\y(SELECT|PERFORM)\y(?:(?!\ySELECT\y|\yPERFORM\y|\yFROM\y)[^;])+\yFROM[[:space:]]+(?:ONLY[[:space:]]+)?\(?[[:space:]]*(?:[[:alnum:]_"]+\.)?"?([[:alnum:]_]+)"?((?:(?!\yORDER[[:space:]]+BY\y(?![^(;]*\))|\yFOR[[:space:]]+(?:(?:NO[[:space:]]+)?KEY[[:space:]]+)?(?:UPDATE|SHARE)\y)[^;])*)(?:\yFOR[[:space:]]+(?:(?:NO[[:space:]]+)?KEY[[:space:]]+)?(?:UPDATE|SHARE)(?:[[:space:]]+OF[[:space:]]+[[:alnum:]_.",[:space:]]+)?(?:[[:space:]]+(?:NOWAIT|SKIP[[:space:]]+LOCKED))?[[:space:]]*)+(?:;|\yLOOP\y)',
        'gi'
    ) AS lck(m)
    CROSS JOIN LATERAL (

        SELECT regexp_replace(lck.m[3], '''(?:''''|[^''])*''', '''''', 'g') AS clean_where
    ) cw
    WHERE 

        cw.clean_where !~* '\yWHERE\y'
        

        OR cw.clean_where ~* '(\yIN[[:space:]]*\(|\yANY[[:space:]]*\(|\yOR\y|\yBETWEEN\y|\yLIKE\y|\yILIKE\y|\ySIMILAR[[:space:]]+TO\y|\yIS[[:space:]]+(?:NOT[[:space:]]+)?NULL\y|\yLIMIT\y|\yFETCH[[:space:]]+(?:FIRST|NEXT)\y|<>|!=|<=|>=|<(?![>=])|(?<![<>!=])>(?!=)|~~|!~|~)'
        

        OR NOT EXISTS (
            SELECT 1
            FROM pg_catalog.pg_class tc
            INNER JOIN pg_catalog.pg_namespace tn ON tn.oid = tc.relnamespace
            INNER JOIN pg_catalog.pg_index i ON i.indrelid = tc.oid
            WHERE tc.relname = lower(lck.m[2])
              AND tn.nspname NOT IN ('pg_catalog', 'information_schema', 'pg_toast')
              AND i.indisunique = TRUE
              AND i.indpred IS NULL

              AND NOT EXISTS (
                  SELECT 1
                  FROM pg_catalog.pg_attribute a
                  WHERE a.attrelid = tc.oid
                    AND a.attnum > 0
                    AND a.attisdropped = FALSE
                    AND (
                        a.attnum = ANY (i.indkey[0 : i.indnkeyatts - 1])
                        OR EXISTS (
                            SELECT 1
                            FROM pg_catalog.pg_depend d
                            WHERE d.classid = 'pg_class'::regclass
                              AND d.objid = i.indexrelid
                              AND d.refclassid = 'pg_class'::regclass
                              AND d.refobjid = tc.oid
                              AND d.refobjsubid = a.attnum
                        )
                    )
                    AND cw.clean_where !~* (
                        '\y' || a.attname || '\y[[:space:]]*\)*(?:::[[:alnum:]_." ]+)?\)*[[:space:]]*=[^=>]|(?<![<>!=])=[[:space:]]*[[:alnum:]_."(]*\y' || a.attname || '\y'
                    )
              )
        )
)
ORDER BY r.routine_schema, r.routine_name, r.parameters;

Fixing Suggestion

Add an explicit ORDER BY clause on the primary key or unique identifier of the locked table immediately before the locking clause (for example, SELECT ... FROM table_name WHERE ... ORDER BY id FOR NO KEY UPDATE; or ORDER BY id FOR SHARE;) so that all concurrent transactions acquire row locks in a consistent, deterministic order.

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:

Concurrency control

Queries of this category provide information about concurrency control.

Triggers and rules

Queries of this category provide information about triggers and rules in a database.

User-defined routines

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

NameDescription
Concurrency controlQueries of this category provide information about concurrency control.
Triggers and rulesQueries of this category provide information about triggers and rules in a database.
User-defined routinesQueries of this category provide information about the user-defined routines