Search code examples
python-3.xpsycopg2sql-execution-planexplain

Print SQL execution plan with python's module psycopg2


Is there any way I can print the information from a SQL execution plan to see it in my Terminal when using python and the psycopg2 module?

I tried the following, but nothing is shown in the Terminal:

cur.execute(cur.mogrify('explain analyze ' + sql_query, vals)

and using the print returns None:

print(cur.execute(cur.mogrify('explain analyze ' + sql_query, vals))

From this question, I also tried the following, but did not work either:

cur.execute("LOAD 'auto_explain';")
cur.execute("SET auto_explain.log_min_duration = {min_ms};".format(min_ms=0))
cur.execute(sql_query, vals)

Solution

  • Just after posting the question I figured out the answer. Quite basic actually. I just had to fetch it, like with any other SELECT command.

    In case anybody else has the same question:

    cur.execute(cur.mogrify('explain analyze ' + sql_query, vals))
    analyze_fetched = cur.fetchall()
    print(analyze_fetched)