0

I have no idea why this error is appearing. The query was working fine and then I tried making it prettier and then this happens

UPDATE "topTenCategories" SET "membersCount" =  "tempTable"."newVal" FROM 
    ( 
        VALUES 
        (
            SELECT count(*), "g"."id" FROM 
            "groups" AS "g" 
            LEFT JOIN 
            "groupMembers" As "gm" 
            ON "g"."id" = "gm"."groupId" 
            WHERE "g"."isCategory" is true and "g"."parentCategoryId" is null group by ("g"."id")
        )
    ) AS tempTable ("newVal", "id")
    WHERE "topTenCategories"."groupId" = "tempTable"."id";
ERROR:  syntax error at or near "SELECT"
LINE 5:                 SELECT count(*), "g"."id" FROM 
                        ^
SQL state: 42601
Character: 137

Any help would be greatly appreciated

2
  • 2
    Or like this ? with "tempTable" as ( SELECT count(*) as "newVal", "g"."id" FROM "groups" AS "g" LEFT JOIN "groupMembers" As "gm" ON "g"."id" = "gm"."groupId" WHERE "g"."isCategory" is true and "g"."parentCategoryId" is null group by ("g"."id") ) UPDATE "topTenCategories" SET "membersCount" = "tempTable"."newVal" from "tempTable" WHERE "topTenCategories"."groupId" = "tempTable"."id"; Commented Jun 30, 2021 at 9:18
  • @Philippe this one works, thanks. But what is the issue in my query Commented Jun 30, 2021 at 9:20

1 Answer 1

1

You can't put a SELECT into a values clause like that. The VALUES clause is intended for constant values and is not needed here.

UPDATE "topTenCategories" 
    SET "membersCount" =  tempTable."newVal" 
FROM ( 
  SELECT count(*), "g"."id" 
  FROM "groups" AS "g" 
    LEFT JOIN "groupMembers" As "gm" ON "g"."id" = "gm"."groupId" 
  WHERE "g"."isCategory" is true 
    and "g"."parentCategoryId" is null group by ("g"."id")
) AS tempTable("newVal", "id")
WHERE "topTenCategories"."groupId" = tempTable."id";

You also need to remove the double quotes when you reference temptable as the quotes make it case sensitive and tempTable is a different name than "tempTable"

In general it's highly recommended to avoid those dreaded quoted identifiers to begin with.

Sign up to request clarification or add additional context in comments.

1 Comment

thanks a lot. Sadly the system I am working started off with camelCase so I need to follow along.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.