Re: query not using index for descending records?

From: Bruno Wolff III <bruno(at)wolff(dot)to>
To: email lists <lists(at)darrenmackay(dot)com>
Cc: pgsql-sql(at)postgresql(dot)org
Subject: Re: query not using index for descending records?
Date: 2004-01-29 13:18:47
Message-ID: 20040129131847.GE17068@wolff.to
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

On Thu, Jan 29, 2004 at 22:18:08 +1000,
email lists <lists(at)darrenmackay(dot)com> wrote:
> Limit (cost=0.00..2.31 rows=20 width=12)
> -> Index Scan using idx_trafficlogs_datetime_id on trafficlogs
> (cost=0.00..1057.89 rows=9172 width=12)
> (2 rows)
>
> however, I am wanting to return the last 20 records. I have been using:
>
> explain select datetime,id from trafficlogs order by datetime,id desc
> limit 20;

You probably don't want to do that. The DESC only applies to the one
expression it follows. What you want is probably:
explain select datetime,id from trafficlogs order by datetime desc,id desc
limit 20;

The index won't get used because with id and datetime being checked in
different orders, only the first part of the index is usable. And probably
that wasn't selective enough for an index scan to be used.

In response to

Responses

Browse pgsql-sql by date

  From Date Subject
Next Message Achilleus Mantzios 2004-01-29 13:29:11 Re: query not using index for descending records?
Previous Message Viorel Dragomir 2004-01-29 13:11:44 Re: