Re: LIMIT and UNION ALL

From: Robert Klemme <shortcutter(at)googlemail(dot)com>
To: Dave Johansen <davejohansen(at)gmail(dot)com>
Cc: pgsql-performance <pgsql-performance(at)postgresql(dot)org>
Subject: Re: LIMIT and UNION ALL
Date: 2011-05-18 15:54:47
Message-ID: BANLkTimhKEfamSutk7HJdyVvosg7c_bpPw@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-performance

On Wed, May 18, 2011 at 5:26 PM, Dave Johansen <davejohansen(at)gmail(dot)com> wrote:
> I am using Postgres 8.3.3 and I have a VIEW which is a UNION ALL of two
> tables but when I do a select on the view using a LIMIT, it scans the entire
> tables and takes significantly longer than writing out the query with the
> LIMITs in the sub-queries themselves. Is there a solution to get the view to
> perform like the query with the LIMIT explicitly placed in the sub-queries?

Can you show DDL and queries?

The query with the LIMIT on the subqueries and the one with the LIMIT
on the overall query are not semantically equivalent. Since you can
have an ORDER BY before the LIMIT on the query with the limit on the
view the database must have all the rows before it can apply the
ordering and properly determine the limit. Although it might be
possible to determine under particular circumstances that only one of
the tables needs to be queried or tables need only be queried
partially I deem that quite complex. I do not know whether Postgres
can do such optimizations but for that we would certainly need to see
the concrete example (including constraint and indexes).

Kind regards

robert

--
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/

In response to

Responses

Browse pgsql-performance by date

  From Date Subject
Next Message Pavel Stehule 2011-05-18 15:59:47 Re: LIMIT and UNION ALL
Previous Message Dave Johansen 2011-05-18 15:26:02 LIMIT and UNION ALL