Received: from sss.pgh.pa.us (sss.pgh.pa.us [209.114.132.154]) by mail.postgresql.org (8.11.1/8.11.1) with ESMTP id f0I3JF092197 for ; Wed, 17 Jan 2001 22:19:15 -0500 (EST) (envelope-from tgl@sss.pgh.pa.us) Received: from sss2.sss.pgh.pa.us (tgl@localhost [127.0.0.1]) by sss.pgh.pa.us (8.11.1/8.11.1) with ESMTP id f0I3J0J22933; Wed, 17 Jan 2001 22:19:00 -0500 (EST) To: Carolyn Wong cc: "pgsql-sql@postgresql.org" Subject: Re: update help In-reply-to: <3A665AE3.CE43178B@greatpacific.com.au> References: <3A665AE3.CE43178B@greatpacific.com.au> Comments: In-reply-to Carolyn Wong message dated "Thu, 18 Jan 2001 13:54:27 +1100" Date: Wed, 17 Jan 2001 22:18:59 -0500 Message-ID: <22930.979787939@sss.pgh.pa.us> From: Tom Lane X-Archive-Number: 200101/204 X-Sequence-Number: 869 Carolyn Wong writes: > I'd like to know what's the correct SQL statement to do the following: > update t1 a > set a.amount = sum(b.amount) > from t2 b > where a.id = b.id Try UPDATE t1 SET amount = (select sum(b.amount) from t2 b WHERE t1.id = b.id); Or possibly you want UPDATE t1 SET amount = (select sum(b.amount) from t2 b WHERE t1.id = b.id) WHERE EXISTS (select * FROM t2 b WHERE t1.id = b.id); depending on whether you mean to zero out any t1 rows that have no matching rows in t2. Note that you cannot attach an alias name to the target table, you have to use its real name in the subselects. There was a thread about this very issue a few months ago, and IIRC we decided that an aggregate in an UPDATE doesn't have well-defined semantics. The SQL92 spec explicitly disallows it. Right now PG will take it, but we probably do something pretty surprising :-( regards, tom lane