Query runs slower as prepared statement - identical execution plans

From: Thomas Kellerer <shammat(at)gmx(dot)net>
To: pgsql-performance(at)postgresql(dot)org
Subject: Query runs slower as prepared statement - identical execution plans
Date: 2022-01-26 07:18:59
Message-ID: 919dfbb7-8704-d93d-07c1-51446b3c07bf@gmx.net
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-performance

Hello,

I have a strange case of a query that runs substantially slower when run as a
Java PreparedStatement with placeholders, compared to using constant values in
the SQL string.

In my experience, the reason for this is usually a different execution plan for the
prepared statement.

However in this case, the plans are identical but the prepared statements runs substantially
slower than the "non-prepared" plan: 1800ms to 2000ms vs. 250ms to 350ms

I can't disclose the query, but the basic structure is this:

select ...
from some_table
where jsonb_column #>> $1 = ANY ($2)
and some_uuid_column = ANY (.....)

For various reasons the list of values for the some_uuid_column = ANY(..) condition
is always passed as constant values.

The plan is quite reasonable using a Bitmap Heap Scan in both cases on "some_uuid_column"

I uploaded the (anonymized) plans to explain.depesz:

Fast execution: https://explain.depesz.com/s/QyFR
Slow execution: https://explain.depesz.com/s/mcQz

The "prepared" plan was created using psql, not through JDBC:
PREPARE p1(text,text) AS ...

EXPLAIN (analyze, buffers, timing, verbose)
EXECUTE p1 ('{...}', '{....}')

But the runtime is pretty much what I see when doing this through Java.

My question is: why is processing the query through a prepared statement so much slower?

This happens on a test system running Postgres 13.2 on CentOS, and another test system
running 13.5 on Ubuntu.

For the time being, we can switch off the use of a PreparedStatement, but I'm also
interesting to know the underlying root cause.

Any ideas?

Browse pgsql-performance by date

  From Date Subject
Next Message Les 2022-02-04 09:11:31 Terribly slow query with very good plan?
Previous Message Michael Lewis 2022-01-24 17:52:40 Re: Slow query fixed by replacing equality with a nested query