Postgres query plan changes for identical query when using pg_hint_plan

463 Views Asked by At

(Postgres 11.7)

I'm using the Rows pg_hint_plan hint to dynamically fix a bad row-count estimate.

My query accepts an array of arguments, which get unnested and joined onto the rest of the query as a predicate. By default, the query planner always assumes this array-argument contains 100 records, whereas in reality this number could be very different. This bad estimate was resulting in poor query plans. I set the number of rows definitively from within the calling application, by changing the hint text per query.

This approach seems to work sometimes, but I see some strange behaviour testing the query (in DBeaver).

If I start with a brand new connection, when I explain the query (or indeed just run it), the hint seems to be ignored for the first 6 executions, but thereafter it starts getting interpreted correctly. This is consistently reproducible: I see the offending row count estimates change on the 7th execution on a new connection.

More interestingly, the query also uses some (immutable) functions to do some lookup operations. If I remove these and replace them with an equivalent CTE or sub-select, this strange behaviour seems to disappear, and the hints are evaluated correctly all the time, even on a brand new connection.

What could be causing it to not honour the pg_hint_plan hints until after 6 requests have been made in that session? Why does the presence of the functions have a bearing on the hints?

1

There are 1 best solutions below

5
Laurenz Albe On

Since you are using JDBC, try setting the prepareThreshold connection parameter to 1, as detailed in the documentation.

That will make the driver use a server prepared statement as soon as possible, ond it seems like this extension only works in that case.