From: Tom Lane <tgl@sss.pgh.pa.us>
To: Jason Coene <jcoene@gotfrag.com>
Cc: 'Merlin Moncure' <merlin.moncure@rcsonline.com>
Cc: pgsql-performance@postgresql.org
Subject: Re: Hardware upgrade for a high-traffic database
Date: Wed, 11 Aug 2004 19:20:04 -0400
Message-ID: <21682.1092266404@sss.pgh.pa.us> (raw)
In-Reply-To: <200408112118.i7BLIR0E097522@mail.gotfrag.com>
References: <200408112118.i7BLIR0E097522@mail.gotfrag.com>
"Jason Coene" <jcoene@gotfrag.com> writes:
> A good example, a comments table where users submit TEXT data. A common
> query is to find the last 5 comments a user has submitted. The scan, while
> using an index, takes a considerable amount of time (> 0.5 sec is about as
> good as it gets). Again, it's using an index on the single WHERE clause
> (userid = int). The field that's used to ORDER BY (timestamp) is also
> indexed.
You mean you are doing
SELECT ... WHERE userid = 42 ORDER BY timestamp DESC LIMIT 5;
and hoping that separate indexes on userid and timestamp will get the
job done? They won't. There are only two possible plans for this,
neither very good: select all of user 42's posts and sort them, or
scan timewise backwards through *all* posts looking for the last 5 from
user 42.
If you do this enough to justify a specialized index, I would suggest a
two-column index on (userid, timestamp). You will also need to tweak
the query, because the planner is not quite smart enough to deduce that
such an index is applicable to the given sort order:
SELECT ... WHERE userid = 42 ORDER BY userid DESC, timestamp DESC LIMIT 5;
This should generate an index-scan-backwards plan that will execute nigh
instantaneously, because it will only fetch the rows you really want.
You might or might not be able to drop the separate indexes on userid
and timestamp, depending on what other queries you might have that need
them. But you should be paying attention to what plans you are really
getting (see EXPLAIN) rather than just assuming that some indexes chosen
at random will do what you need.
regards, tom lane
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 using the --to and --cc options:
reply via email
To: pgsql-performance@postgresql.org
Cc: tgl@sss.pgh.pa.us, jcoene@gotfrag.com, merlin.moncure@rcsonline.com
Subject: Re: Hardware upgrade for a high-traffic database
In-Reply-To: <21682.1092266404@sss.pgh.pa.us>
* 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