Junior — Middle
How can you view the execution plan of an SQL query and its timing metrics?
sobes.tech AI
Answer from AI
To view the execution plan of an SQL query and its timing metrics, the EXPLAIN command or its extensions are usually used, which show how the database will execute the query.
In PostgreSQL, for example, you can run:
EXPLAIN ANALYZE SELECT * FROM table WHERE condition;
This will show the execution plan with real timing metrics.
In Python, if you're using Django, you can get the plan like this:
from django.db import connection
query = "SELECT * FROM myapp_mymodel WHERE field = %s"
params = ['value']
with connection.cursor() as cursor:
cursor.execute(f"EXPLAIN ANALYZE {query}", params)
plan = cursor.fetchall()
for row in plan:
print(row[0])
For other DBMSs, the syntax may differ, but the idea is the same — use EXPLAIN or an equivalent to get the plan and evaluate query efficiency.