Ask Your Question
2

In PLPGSQL, what is the method for obtaining a query plan and storing it in a table, by executing a dynamic query within an anonymous code block?

asked 2023-06-08 16:34:47 +0000

qstack gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2023-06-08 16:47:02 +0000

djk gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-06-08 16:34:47 +0000

Seen: 19 times

Last updated: Jun 08 '23