Received: from localhost (unknown [200.46.204.183]) by postgresql.org (Postfix) with ESMTP id 633C52E2D7D for ; Tue, 12 Feb 2008 12:18:13 -0400 (AST) Received: from postgresql.org ([200.46.204.71]) by localhost (mx1.hub.org [200.46.204.183]) (amavisd-maia, port 10024) with ESMTP id 40984-05 for ; Tue, 12 Feb 2008 12:18:07 -0400 (AST) Received: from sss.pgh.pa.us (sss.pgh.pa.us [66.207.139.130]) by postgresql.org (Postfix) with ESMTP id 8ED902E2D63 for ; Tue, 12 Feb 2008 12:18:07 -0400 (AST) Received: from sss2.sss.pgh.pa.us (tgl@localhost [127.0.0.1]) by sss.pgh.pa.us (8.14.2/8.14.2) with ESMTP id m1CGI5Ou027295; Tue, 12 Feb 2008 11:18:05 -0500 (EST) To: "Linux Guru" cc: pgsql-performance@postgresql.org Subject: Re: Update with Subquery Performance In-reply-to: <3caa866c0802120032r7b7eb672s98d38f1351622424@mail.gmail.com> References: <3caa866c0802110306rcb5e72dyd264ff330c61f8ae@mail.gmail.com> <2982.1202749162@sss.pgh.pa.us> <3caa866c0802120032r7b7eb672s98d38f1351622424@mail.gmail.com> Comments: In-reply-to "Linux Guru" message dated "Tue, 12 Feb 2008 13:32:29 +0500" Date: Tue, 12 Feb 2008 11:18:05 -0500 Message-ID: <27294.1202833085@sss.pgh.pa.us> From: Tom Lane X-Virus-Scanned: Maia Mailguard 1.0.1 X-Archive-Number: 200802/117 X-Sequence-Number: 28659 "Linux Guru" writes: > Analyzing did not help, here is the out of EXPLAIN ANALYZE of update query > "Seq Scan on dummy (cost=0.00..56739774.24 rows=23441 width=275) (actual > time=18.927..577929.014 rows=22712 loops=1)" > " SubPlan" > " -> Aggregate (cost=2420.41..2420.43 rows=1 width=19) (actual time= > 25.423..25.425 rows=1 loops=22712)" > " -> Seq Scan on dummy "temp" (cost=0.00..2416.01 rows=586 > width=19) (actual time=0.049..17.834 rows=2414 loops=22712)" > " Filter: ((product)::text = ($0)::text)" > "Total runtime: 578968.885 ms" Yeah, that's just not going to be fast. An index on the product column might help a bit, but the real issue is that you're repetitively calculating the same aggregates. I think you need a separate temp table, along the lines of create temp table dummy_agg as select product, (case when sum(pd) <> 0 then sum(gd)/sum(pd)*100 else 0 end) as s from dummy group by product; create index dummy_agg_i on dummy_agg(product); -- optional update dummy set gp= (select s from dummy_agg where dummy_agg.product = dummy.product); The index would only be needed if you expect a lot of rows (lot of different product values). regards, tom lane