Sobes.tech
Junior — Middle

What methods can be used to improve the efficiency of SQL query execution?

sobes.tech AI

Answer from AI

To improve the efficiency of executing SQL queries, the following methods can be used:

  • Indexing: creating indexes on columns frequently used in conditions speeds up search.
  • Query optimization: avoid redundant JOINs, select only necessary fields (SELECT specific columns instead of SELECT *).
  • Caching: store results of frequently executed queries.
  • Batch processing: perform multiple operations in a single query if possible.
  • Using prepared statements: increases performance and security.

Example of using prepared statements in Python with the sqlite3 library:

import sqlite3

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

# Prepared statement with a parameter
cursor.execute('SELECT * FROM users WHERE age > ?', (30,))
rows = cursor.fetchall()

for row in rows:
    print(row)

conn.close()