To obtain a query plan and store it in a table by executing a dynamic query within an anonymous code block in PLPGSQL, you can use the following method:
DECLARE
query_text text;
plan_json json;
BEGIN
query_text := 'SELECT * FROM table_name;';
plan_json := (EXPLAIN (FORMAT JSON) EXECUTE query_text);
INSERT INTO plan_table (query, plan)
VALUES (query_text, plan_json);
END;
This code block declares a query_text
variable to hold the dynamic SQL query, and a plan_json
variable to hold the query plan in JSON format. The EXPLAIN
command is used to obtain the query plan, and the EXECUTE
command is used to execute the dynamic query.
The query plan is then stored in the plan_json
variable, which is inserted into a plan_table
along with the original query text using an INSERT
statement.
Note that plan_table
must be created beforehand, with columns query
and plan
to store the query text and plan data, respectively.
Asked: 2023-06-08 16:34:47 +0000
Seen: 19 times
Last updated: Jun 08 '23