Sobes.tech
Junior — Middle

How can you see the execution plan of an SQL query?

sobes.tech AI

Answer from AI

To see the execution plan of an SQL query, you usually use the EXPLAIN command before the query itself. In Python, this can be done through a database interaction library (e.g., psycopg2 for PostgreSQL).

Example for PostgreSQL:

import psycopg2

conn = psycopg2.connect(dbname="testdb", user="user", password="pass")
cursor = conn.cursor()

query = "SELECT * FROM users WHERE age > 30"
explain_query = "EXPLAIN " + query

cursor.execute(explain_query)
plan = cursor.fetchall()
for row in plan:
    print(row[0])

cursor.close()
conn.close()

EXPLAIN shows how the database plans to execute the query — what indexes it uses, join types, etc. Some databases have an extended EXPLAIN ANALYZE that executes the query and shows actual costs.

For other databases, the syntax may differ, but the idea is to use EXPLAIN or its equivalent.