Re: select max(id) from aTable is very slow

From: Richard Huxton <dev(at)archonet(dot)com>
To: David Teran <david(dot)teran(at)cluster9(dot)com>
Cc: PgSQL Performance ML <pgsql-performance(at)postgresql(dot)org>
Subject: Re: select max(id) from aTable is very slow
Date: 2004-06-03 13:07:49
Message-ID: 40BF22A5.8060102@archonet.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-performance

David Teran wrote:
> Hi,
>
> we have a table with about 6.000.000 rows. There is an index on a
> column with the name id which is an integer and serves as primary key.
>
> When we execute select max(id) from theTable; it takes about 10
> seconds. Explain analyze returns:

Due to the open-ended nature of PG's aggregate function system, it can't
see inside the max() function to realise it doesn't need all the values.

Fortune favours the flexible however - the simple workaround is to use
the equivalent:
SELECT id FROM theTable ORDER BY id DESC LIMIT 1;

--
Richard Huxton
Archonet Ltd

In response to

Browse pgsql-performance by date

  From Date Subject
Next Message Marcus Whitney 2004-06-03 21:38:03 Re: Pl/Pgsql Functions running simultaneously
Previous Message Tom Lane 2004-06-03 03:51:25 Re: PostgreSQL on VMWare vs Windows vs CoLinux