pg.ddx.io  pgsql-performance@postgresql.org mailing list archive  
help / color / mirror / Atom feed
From: Tom Lane <tgl@sss.pgh.pa.us>
To: Marcio Ribeiro <mribeiro@gmail.com>
Cc: pgsql-performance@postgresql.org
Subject: Re: LIMIT 1 poor query plan
Date: Sat, 10 Oct 2015 10:45:36 -0500
Message-ID: <48410.1444491936@sss.pgh.pa.us> (raw)
In-Reply-To: <CAMAHXRzu6daCPNtOGcGboTAsQ5gs9vdFEsTvACC2b6if9ni2-w@mail.gmail.com>
References: <CAMAHXRzu6daCPNtOGcGboTAsQ5gs9vdFEsTvACC2b6if9ni2-w@mail.gmail.com>
List-Unsubscribe:  <mailto:majordomo@postgresql.org?body=unsub%20pgsql-performance>

Marcio Ribeiro <mribeiro@gmail.com> writes:
> Short question:
> Why would pg optimizer choose a worst (slower) query plan for a
> query with 'LIMIT 1' instead of, say, 'LIMIT 3'?

> Complete scenario:
> Query: 'SELECT * FROM a WHERE a.b_id = 42 ORDER BY created LIMIT 1'
> - b_id is a FK to b;
> - created is a datetime with the time of the creation of the row;
> - both 'b' and 'created' are indexed separately

> This query, with the LIMIT 1, uses the index on created, which is much
> slower (10x) than if it used the index on b_id

It's trying to avoid a sort; or to be less anthropomorphic, the estimated
cost of scanning the "created" index until it hits the first row with
b_id=42 is less than the estimated cost of collecting all the rows with
b_id=42 and then sorting them by "created".  The estimates unfortunately
are kind of shaky because it's hard to predict how many rows will get
skipped before finding one with b_id=42.

If you do this type of query often enough to care about its performance,
you could consider creating a two-column index on (b_id, created)
(in that order).

			regards, tom lane


-- 
Sent via pgsql-performance mailing list (pgsql-performance@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-performance



view thread (3+ messages)  latest in thread

Message-ID: <48410.1444491936@sss.pgh.pa.us>
Permalink:  ../48410.1444491936@sss.pgh.pa.us/
Also on:    postgresql.org/message-id/48410.1444491936@sss.pgh.pa.us

 · 

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 using the --to and --cc options:
  reply via email

  To: pgsql-performance@postgresql.org
  Cc: tgl@sss.pgh.pa.us, mribeiro@gmail.com
  Subject: Re: LIMIT 1 poor query plan
  In-Reply-To: <48410.1444491936@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