Sobes.tech
Junior — Middle

How can you measure the execution time of an SQL query?

sobes.tech AI

Answer from AI

To measure the execution time of an SQL query in Python, you can use the time module to record the time before and after executing the query. For example:

import time
import sqlite3

conn = sqlite3.connect('example.db')
cursor = conn.cursor()

start_time = time.time()
cursor.execute('SELECT * FROM users WHERE age > 30')
rows = cursor.fetchall()
end_time = time.time()

print(f"Query execution time: {end_time - start_time:.6f} seconds")

Some database libraries (e.g., psycopg2 for PostgreSQL) also provide built-in methods for query profiling. For more precise analysis, you can use profilers or database tools, such as EXPLAIN ANALYZE in PostgreSQL.