Re: Query is slow when run for first time; subsequent execution is fast

From: Jeff Janes <jeff(dot)janes(at)gmail(dot)com>
To: Nandakumar M <m(dot)nanda92(at)gmail(dot)com>, "pgsql-performa(dot)" <pgsql-performance(at)postgresql(dot)org>
Subject: Re: Query is slow when run for first time; subsequent execution is fast
Date: 2018-01-10 19:34:17
Message-ID: CAMkU=1yiULP9Gdy1pT2bpVomi4cinNGz8d7-7y+chBOQFg3f6Q@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-performance

On Wed, Jan 10, 2018 at 3:59 AM, Nandakumar M <m(dot)nanda92(at)gmail(dot)com> wrote:

>
> I am not using prepared statements. Postgres documentation and previous
> questions in the pgsql-performance mailing list mention that the query plan
> is cached only when prepared statements are used.
>
> https://www.postgresql.org/message-id/15600.1346885470%40sss.pgh.pa.us
>
> In the above thread Tom Lane mentions that the plan is never cached for
> raw queries. Yet, this is exactly what seems to be happening in my case. Am
> I missing something?
>

The query plan itself is not cached, but all the metadata about the (large
number) of tables used in the query is cached. Apparently reading/parsing
that data is the slow step, not coming up with the actual plan.

> Please let me know how I can make sure the query execution for the first
time is fast too.

Don't keep closing and reopening connections. Use a connection pooler
(pgbouncer, pgpool, whatever pooler is built into your
language/library/driver, etc.) if necessary to accomplish this.

Cheers,

Jeff

In response to

Responses

Browse pgsql-performance by date

  From Date Subject
Next Message POUSSEL, Guillaume 2018-01-11 08:19:39 Slow queries after Windows startup
Previous Message ghiureai 2018-01-10 18:49:41 Re: PG 9.5 2 tables same DDL with diff size