Received: from maia.hub.org (maia-2.hub.org [200.46.204.251]) by mail.postgresql.org (Postfix) with ESMTP id D212A6328F4 for ; Wed, 25 Aug 2010 11:46:21 -0300 (ADT) Received: from mail.postgresql.org ([200.46.204.86]) by maia.hub.org (mx1.hub.org [200.46.204.251]) (amavisd-maia, port 10024) with ESMTP id 37487-03 for ; Wed, 25 Aug 2010 14:46:13 +0000 (UTC) X-Greylist: from auto-whitelisted by SQLgrey-1.7.6 Received: from momjian.us (momjian.us [70.90.9.53]) by mail.postgresql.org (Postfix) with ESMTP id B15F2632890 for ; Wed, 25 Aug 2010 11:46:14 -0300 (ADT) Received: (from bruce@localhost) by momjian.us (8.11.6/8.11.6) id o7PEkBJ21094; Wed, 25 Aug 2010 10:46:11 -0400 (EDT) From: Bruce Momjian Message-Id: <201008251446.o7PEkBJ21094@momjian.us> Subject: Re: using min|max in where In-Reply-To: To: Ben Carbery Date: Wed, 25 Aug 2010 10:46:11 -0400 (EDT) CC: pgsql-sql@postgresql.org X-Mailer: ELM [version 2.4ME+ PL124 (25)] MIME-Version: 1.0 Content-Transfer-Encoding: 7bit Content-Type: text/plain; charset="US-ASCII" X-Virus-Scanned: Maia Mailguard 1.0.1 X-Spam-Status: No, hits=-1.91 tagged_above=-5 required=5 tests=BAYES_00=-1.9, T_RP_MATCHES_RCVD=-0.01 X-Spam-Level: X-Archive-Number: 201008/77 X-Sequence-Number: 34517 Ben Carbery wrote: > Hi, I have some sql like so: > > SELECT min(date) INTO d FROM interest_rate WHERE m_code = NEW.code; > UPDATE interest_rate SET date = NEW.start_date, rate = NEW.initial_rate > WHERE m_code = NEW.code AND date = d; > > Actually this is pgsql but I don't think that matters. > > I am wondering if I can make this more compact by somehow including the > 'min' function in the WHERE clause, but WITHOUT simply moving the select in > there. So not this.. > > UPDATE interest_rate SET date = NEW.start_date, rate = NEW.initial_rate > WHERE m_code = NEW.code AND date = (SELECT min(date) FROM interest_rate > WHERE m_code = NEW.code); > > This is just an example but I seem to find this pattern a lot in my > functions. I think you want the HAVING clause of SELECT. -- Bruce Momjian http://momjian.us EnterpriseDB http://enterprisedb.com + It's impossible for everything to be true. +