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) and include an unnecessary ORDER BY clause when the query can lock at most a single row.

While deterministic row ordering via ORDER BY is essential for preventing deadlocks when a query locks multiple rows, adding ORDER BY to a locking query is completely redundant in two cases:

  • Single-row primary or unique key lookups: When the WHERE clause constrains all columns of a PRIMARY KEY or UNIQUE index using simple equality (=) without OR, IN (...), = ANY (...), range operators, or JOINs, the query is mathematically guaranteed to return at most one row (0 or 1 row). A single row has only one possible lock acquisition order and cannot cause an intra-query ordering deadlock; adding ORDER BY merely clutters the code and can prevent optimizer shortcuts or introduce unnecessary sort overhead if the sort column differs from the lookup index.

  • EXISTS (SELECT ... ORDER BY ... FOR ...) subqueries without LIMIT / FETCH: An EXISTS subquery halts execution and locks only the very first matching row. Including an ORDER BY clause inside an EXISTS subquery without a row-limiting clause forces PostgreSQL to fetch and sort all candidate rows before locking and testing the first row.

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 SELECT or PERFORM query that specifies both an ORDER BY clause and a row-level locking clause (FOR [NO KEY] UPDATE or FOR [KEY] SHARE).

A locking query with ORDER BY is flagged as redundant if:

  • It is an EXISTS (SELECT ... ORDER BY ... FOR ...) subquery that does not use LIMIT, FETCH FIRST/NEXT, or OFFSET; or

  • It is a single-table query (no JOIN) whose WHERE clause contains no multi-row, range, or set predicates (IN, ANY, OR, BETWEEN, inequalities, pattern operators, IS [NOT] NULL, UNION) and constrains all key columns of at least one non-partial PRIMARY KEY or UNIQUE index on the target table in pg_index (supporting both standard column indexes via indkey and expression unique indexes via pg_depend) using equality (=).



In the returned routine source code, < characters are escaped (&lt;), newline characters are replaced with HTML line break (<br>) tags, and both ORDER BY 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 ~* '\yORDER[[:space:]]+BY\y'
      AND 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(
                regexp_replace(r.raw_src, '<', '&lt;', 'g'),
                '[\r\n]', '<br>', 'g'
            ),
            '(ORDER[[:space:]]+BY)', '<b>\1</b>', 'gi'
        ),
        '(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,
        '(\yEXISTS[[:space:]]*\([[:space:]]*)?\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)[^;])*)\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:]]*)+',
        'gi'
    ) AS lck(m)
    CROSS JOIN LATERAL (

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

        (
            lck.m[1] IS NOT NULL
            AND cw.clean_after_order !~* '(\yLIMIT\y|\yFETCH[[:space:]]+(?:FIRST|NEXT)\y|\yOFFSET\y)'
        )
        
        OR 
        

        (
            cw.clean_where ~* '\yWHERE\y'
            AND cw.clean_where !~* '\yJOIN\y'
            AND 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|\yGROUP[[:space:]]+BY\y|\yUNION\y|\yINTERSECT\y|\yEXCEPT\y|<>|!=|<=|>=|<(?![>=])|(?<![<>!=])>(?!=)|~~|!~|~)'
            AND 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[3])
                  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

Remove the redundant ORDER BY clause from the single-row locking query (or EXISTS subquery). Reserve ORDER BY in locking queries strictly for statements that can lock multiple rows (such as WHERE id IN (...), WHERE id = ANY (...), range filters, or non-unique foreign key lookups) or statements that use LIMIT / FETCH FIRST ... ROWS.

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