Re: Query takes way longer with LIMIT, and EXPLAIN takes way longer than actual query

From: Justin Pryzby <pryzby(at)telsasoft(dot)com>
To: Ken Tanzer <ken(dot)tanzer(at)gmail(dot)com>
Cc: pgsql-performance(at)postgresql(dot)org
Subject: Re: Query takes way longer with LIMIT, and EXPLAIN takes way longer than actual query
Date: 2020-08-14 22:04:24
Message-ID: 20200814220424.GK4561@telsasoft.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-performance

On Fri, Aug 14, 2020 at 02:34:52PM -0700, Ken Tanzer wrote:
> Hi. I've got a query that runs fine (~50ms). When I add a "LIMIT 25" to
> it though, it takes way longer. The query itself then takes about 4.5
> seconds. And when I do an explain, it takes 90+ seconds for the same query!

Due to the over-estimated rowcount, the planner believes that (more) rows will
be output (sooner) than they actually are:

-> Nested Loop Semi Join (cost=47.11..31367302.81 ROWS=611586 width=336) (actual time=47.098..97236.123 ROWS=25 loops=1)

So it thinks there's something to be saved/gained by using a plan that has a
low startup cost. But instead, it ends up running for a substantial fraction
of the total (estimated) cost.

As for the "explain is more expensive than the query", that could be due to
timing overhead, as mentioned here. Test with "explain (timing off)" ?
https://www.postgresql.org/docs/12/using-explain.html#USING-EXPLAIN-CAVEATS

--
Justin

In response to

Responses

Browse pgsql-performance by date

  From Date Subject
Next Message Ken Tanzer 2020-08-14 22:40:40 Re: Query takes way longer with LIMIT, and EXPLAIN takes way longer than actual query
Previous Message Ken Tanzer 2020-08-14 21:34:52 Query takes way longer with LIMIT, and EXPLAIN takes way longer than actual query