Sobes.tech
Junior — Middle

In what cases is it recommended to use pure SQL queries without ORM or other abstractions?

sobes.tech AI

Answer from AI

Pure SQL queries without ORM or other abstractions are recommended to be used in the following cases:

  • When maximum performance and control over queries are needed, for example, for complex analytical queries or optimization.
  • If the ORM does not support specific database features required by the project.
  • When working with very complex queries where ORM might generate redundant or inefficient SQL.
  • In projects with limited resources, where an additional layer of abstraction is undesirable.
  • For quick prototyping or one-time scripts where using ORM is excessive.

An example of a simple pure SQL query in Python using the psycopg2 library for PostgreSQL:

import psycopg2

conn = psycopg2.connect(dbname="testdb", user="user", password="pass")
cursor = conn.cursor()
cursor.execute("SELECT id, name FROM users WHERE active = TRUE")
rows = cursor.fetchall()
for row in rows:
    print(row)
conn.close()