Executing Raw SQL
Sometimes raw SQL is the simplest solution:
- complex reporting queries
- bulk updates
- vendor-specific SQL features
The ORM is great, but you can mix approaches.
Executing SQL with SQLAlchemy
In modern SQLAlchemy, you typically use text()text().
from sqlalchemy import text
with db.engine.connect() as conn:
result = conn.execute(text("SELECT 1"))
print(result.scalar())from sqlalchemy import text
with db.engine.connect() as conn:
result = conn.execute(text("SELECT 1"))
print(result.scalar())Parameter binding (important)
Never build SQL by string concatenation.
from sqlalchemy import text
sql = text("SELECT * FROM users WHERE username = :username")
result = db.session.execute(sql, {"username": "ravi"})
rows = result.fetchall()from sqlalchemy import text
sql = text("SELECT * FROM users WHERE username = :username")
result = db.session.execute(sql, {"username": "ravi"})
rows = result.fetchall()This prevents SQL injection.
When to prefer ORM
Use ORM when:
- youβre doing normal CRUD
- you want relationships and model validation
Use raw SQL when:
- query is complex and ORM becomes unreadable
- you need performance tuning (carefully)
Best approach: be pragmatic and keep code understandable.
If this helped you, consider buying me a coffee β
Buy me a coffeeWas this page helpful?
Let us know how we did
