Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I execute an "Explain" statement with a prepared query in PostgrSQL that has bind parameters?

Tags:

postgresql

I would like to be able to execute an explain statement on a query that has bind parameters. For example:

EXPLAIN SELECT * FROM metasyntax WHERE id = $1;

When I attempt to execute this, I get the following error:

ERROR: bind message supplies 0 parameters, but prepared statement "" requires 1

I understand it's telling me that it wants me to supply a value for the query. However, I may not necessarily know the answer to that. In other SQL dialects such as Oracle, it will generate an explain plan without needing me to supply a value for the parameter.

Is it possible to get an explain plan without binding to an actual value? Thanks!

like image 606
Jason Thompson Avatar asked Jul 03 '17 17:07

Jason Thompson


People also ask

How do I explain query in PostgreSQL?

EXPLAIN is very useful for understanding the performance of a Postgres query. It returns the execution plan generated by PostgreSQL query planner for a given statement. The EXPLAIN command specifies whether the tables referenced in a statement will be searched using an index scan or a sequential scan.

How query is execute in PostgreSQL?

To do this in PL/pgSQL, use the PERFORM statement: PERFORM query ; This executes query and discards the result. Write the query the same way you would write an SQL SELECT command, but replace the initial keyword SELECT with PERFORM .

How do I bind variables in PostgreSQL?

In PostgreSQL, bind variables are numbers preceeded by a $ sign. When using SQL Relay bind functions, to refer to an Oracle, Sybase or MS SQL Server bind variable, you should use its name without the preceeding colon.

What is the difference between prepared statements and parameterized queries?

Prepared statements are statement already interpreted, the DBMS change parameters and the query starts immediately. This is a feature of certain DBMS and you can achieve fast response (comparable with stored procedures). Parametrized statement are just a way you compose the query string in your programming languages.


2 Answers

Assuming the parameter is an integer:

PREPARE x(integer) AS SELECT * FROM metasyntax WHERE id = $1;

Then run the following six times, where “42” is a representative value:

EXPLAIN (ANALYZE, BUFFERS) EXECUTE x(42);

Normally PostgreSQL will switch to a generic plan for the sixth run, and you will see a plan that contains the placeholder $1.

like image 151
Laurenz Albe Avatar answered Oct 19 '22 19:10

Laurenz Albe


No.

The optimiser is allowed to change the query plan based on the parameter. Imagine if the parameter was null - it's obvious that no rows will be returned, so the DB may return an empty rowset instantly.

Just use a representative value.

like image 21
Bohemian Avatar answered Oct 19 '22 17:10

Bohemian