[Solved] PostgreSql: cannot use aggregate function in UPDATE
Looking to automatically optimize YOUR SQL query? Start for free.

EverSQL Database Performance Knowledge Base

PostgreSql: cannot use aggregate function in UPDATE

Database type:

I have an Oracle query that I ported to PostgreSql:

UPDATE "SPD_PG"."TT_SPLDR_11A2F324_29" 
SET "SECT_ORDER" = MAX("SECTIONS"."SECT_ORDER")+1 FROM "SPD_PG"."SECTIONS"
INNER JOIN "SPD_PG"."META_SECTIONS" ON ("SECTIONS"."META_SECT_ID"="META_SECTIONS"."META_SECT_ID")
WHERE ("META_SECTIONS"."META_SECT_ORDER"="TT_SPLDR_11A2F324_29"."META_SECT_ORDER"-1)
AND ("SECTIONS"."DOC_ID"="TT_SPLDR_11A2F324_29"."DOC_ID")
AND ("TT_SPLDR_11A2F324_29"."META_SECT_ORDER">0)

This give me: ERROR: cannot use aggregate function in UPDATE, seems PostgreSql doesn't support MAX in Update statements.

However if I rewrite the query as follows:

UPDATE "SPD_PG"."TT_SPLDR_11A2F324_29" 
SET "SECT_ORDER" = "MAX_VALUE" FROM (
  SELECT MAX("SECTIONS"."SECT_ORDER")+1 AS "MAX_VALUE" FROM "SPD_PG"."SECTIONS"
  INNER JOIN "SPD_PG"."META_SECTIONS" ON ("SECTIONS"."META_SECT_ID"="META_SECTIONS"."META_SECT_ID")
  WHERE ("META_SECTIONS"."META_SECT_ORDER"="TT_SPLDR_11A2F324_29"."META_SECT_ORDER"-1)
  AND ("SECTIONS"."DOC_ID"="TT_SPLDR_11A2F324_29"."DOC_ID")
  AND ("TT_SPLDR_11A2F324_29"."META_SECT_ORDER">0)
) "TBL_ALIAS"

it says ERROR: subquery in FROM cannot refer to other relations of same query level.

So I can't figure out how to write this query.

How to optimize this SQL query?

The following recommendations will help you in your SQL tuning process.
You'll find 3 sections below:

  1. Description of the steps you can take to speed up the query.
  2. The optimal indexes for this query, which you can copy and create in your database.
  3. An automatically re-written query you can copy and execute in your database.
The optimization process and recommendations:
  1. Create Optimal Indexes (modified query below): The recommended indexes are an integral part of this optimization effort and should be created before testing the execution duration of the optimized query.
Optimal indexes for this query:
CREATE INDEX tt_11a2f324_idx_doc_id_meta_order ON TT_SPLDR_11A2F324_29 (DOC_ID,META_SECT_ORDER);
The optimized query:
SELECT
        "SPD_PG"."TT_SPLDR_11A2F324_29"."SECT_ORDER" 
    FROM
        "SPD_PG"."TT_SPLDR_11A2F324_29" 
    WHERE
        (
            "META_SECTIONS"."META_SECT_ORDER" = "TT_SPLDR_11A2F324_29"."META_SECT_ORDER" - 1
        ) 
        AND (
            "SECTIONS"."DOC_ID" = "TT_SPLDR_11A2F324_29"."DOC_ID"
        ) 
        AND (
            "TT_SPLDR_11A2F324_29"."META_SECT_ORDER" > 0
        )

Related Articles



* original question posted on StackOverflow here.