Received: from coldresist.com (cr271446-a.rchmd1.bc.wave.home.com [24.113.128.171]) by postgresql.org (8.11.3/8.11.1) with ESMTP id f57J6sE63390 for ; Thu, 7 Jun 2001 15:06:55 -0400 (EDT) (envelope-from gml1@coldresist.com) Received: from idyllic.coldresist.com ([192.168.0.7]) by coldresist.com (8.11.2/8.11.2) with ESMTP id f57JA7x19057 for ; Thu, 7 Jun 2001 12:10:07 -0700 Message-Id: <5.1.0.14.0.20010607120835.02bbbd60@coldresist.com> X-Sender: gml1@coldresist.com X-Mailer: QUALCOMM Windows Eudora Version 5.1 Date: Thu, 07 Jun 2001 12:13:50 -0700 To: From: Gerald Gutierrez Subject: Re: Getting row with id=max(id) In-Reply-To: References: <5.1.0.14.0.20010607100000.02b8ae58@coldresist.com> Mime-Version: 1.0 Content-Type: text/plain; charset="us-ascii"; format=flowed X-Archive-Number: 200106/114 X-Sequence-Number: 3334 At 07:31 PM 6/7/2001 +0200, Peter Eisentraut wrote: > > SELECT * FROM mytable WHERE id=(SELECT MAX(id) FROM mytable); > > SELECT * FROM mytable ORDER BY id DESC LIMIT 1; >The second is generally thought to be faster, at least if you use the >latest version of PostgreSQL. This is quite amusing actually. To get the maximum of a column, the (much more) convoluted way is much faster than the intuitive way: => explain select id from mytable order by seed desc limit 1; NOTICE: QUERY PLAN: Index Scan Backward using mytable _pkey on mytable (cost=0.00..794189.09 rows=5358342 width=4) EXPLAIN => explain select max(id) from mytable ; NOTICE: QUERY PLAN: Aggregate (cost=103152.27..103152.27 rows=1 width=4) -> Seq Scan on mytable (cost=0.00..89756.42 rows=5358342 width=4) EXPLAIN Perhaps if the server internally rewrote the second query into the first, it would make the intuitive version much faster. The same can be done for min() and perhaps other functions as well.