Generic Q about max(id) vs ORDER BY ID DESC LIMIT 1

From: felix(at)crowfix(dot)com
To: pgsql-general(at)postgresql(dot)org
Subject: Generic Q about max(id) vs ORDER BY ID DESC LIMIT 1
Date: 2005-10-24 21:57:36
Message-ID: 20051024215736.GA31549@crowfix.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

Having been surprised a few times myself by EXPLAIN showing a
sequential scan instead of using an index, and having seen so many
others surprised by it, I hope I am not asking a similar question.

We recently upgraded our db servers, both old and new running 8.0, and
one casualty was forgetting to add the nightly VACUUM ANALYZE.
Inserts were down to 7-8 seconds apiece, but are now back to normal
under a second since the tables were vacuumed.

However, in the process of investigating this, my boss found something
which we do not understand. A table with a primary key 'id' takes 200
seconds to SELECT MAX(id), but is as close to instantaneous as you'd
want for SELECT ID ORDER BY ID DESC LIMIT 1. I understand why
count(*) has to traverse all records, but why does MAX have to? This
table has about 750,000 rows, rather puny.

I suspect there is either a FAQ which I missed, or no one can answer
without EXPLAIN printouts. I'm hoping there is some generic answer to
something simple I have overlooked.

--
... _._. ._ ._. . _._. ._. ___ .__ ._. . .__. ._ .. ._.
Felix Finch: scarecrow repairman & rocket surgeon / felix(at)crowfix(dot)com
GPG = E987 4493 C860 246C 3B1E 6477 7838 76E9 182E 8151 ITAR license #4933
I've found a solution to Fermat's Last Theorem but I see I've run out of room o

Responses

Browse pgsql-general by date

  From Date Subject
Next Message WireSpot 2005-10-24 21:59:27 Deleting vs foreign keys
Previous Message Jeff Davis 2005-10-24 21:48:51 Re: PostgreSQL vs mySQL, any performance difference for