I am trying to add count, sum, and average values from one table to another, but I end up querying the same data for each value. I’m using PostgreSQL. I’m turning this over to the experts to learn how to make this update statement more efficient. Here it is:
update "table1" set
"col1" = (SELECT COUNT(*) FROM "table2" WHERE "table2Id" = "table1"."table1Id"),
"col2" = (SELECT AVG("someCol") FROM "table2" WHERE "table2Id" = "table1"."table1Id"),
"col3" = (SELECT SUM("someCol") FROM "table2" WHERE "table2Id" = "table1"."table1Id");
I should be able to run a subquery like this once and access the returned values for the update, correct?
SELECT COUNT(*), AVG("someCol"), SUM("someCol") FROM "table2" WHERE "table2Id" = "table1"."table1Id";
Any help is much appreciated.
Try a subquery: