pg.ddx.io  pgsql-sql@postgresql.org mailing list archive  
help / color / mirror / Atom feed
From: Gerald Gutierrez <gml1@coldresist.com>
To: pgsql-sql@postgresql.org
Subject: Re: Getting row with id=max(id)
Date: Thu, 07 Jun 2001 12:13:50 -0700
Message-ID: <5.1.0.14.0.20010607120835.02bbbd60@coldresist.com> (raw)
In-Reply-To: <Pine.LNX.4.30.0106071929140.757-100000@peter.localdomain>
References: <5.1.0.14.0.20010607100000.02b8ae58@coldresist.com>


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.







view thread (8+ messages)  latest in thread

Message-ID: <5.1.0.14.0.20010607120835.02bbbd60@coldresist.com>
Permalink:  ../5.1.0.14.0.20010607120835.02bbbd60@coldresist.com/
Also on:    postgresql.org/message-id/5.1.0.14.0.20010607120835.02bbbd60@coldresist.com

 · 

reply

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Reply to all the recipients from your mail client; the link fills in
  the headers below: reply via email
  Some clients, webmail especially, drop In-Reply-To and References from
  a link, and the reply then starts a new thread: use the mbox below.

  To: pgsql-sql@postgresql.org
  Cc: gml1@coldresist.com
  Subject: Re: Getting row with id=max(id)
  In-Reply-To: <5.1.0.14.0.20010607120835.02bbbd60@coldresist.com>
  References: <5.1.0.14.0.20010607100000.02b8ae58@coldresist.com> <5.1.0.14.0.20010607120835.02bbbd60@coldresist.com>

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox