New: Cookbooks and AI ExplanationsStep-by-Step recipes to solve problems connected to Roadmaps and Cheat Sheets. Need more details? Use AI buttons for structured and simple explanations with concrete examples throughout the whole platform.Take a look
Some of my ORM queries have five joins and take forever to write. Should I just hand-write the SQL instead?
What you'll have at the end
A written rule for your project stating exactly when a query earns raw SQL, plus one flagged query rewritten as safe, parameterized raw SQL and proven to return the same rows as the ORM version.
You need
A SQLAlchemy query that already runs correctly but joins several tables and reads as painful to write, plus the ability to turn on that query's SQL logging and run EXPLAIN on your own database.
Not covered
Fixing a query that fires once per row (that's an eager-loading fix, covered by the N+1 recipe) or loading thousands of rows at once (covered by the bulk-insert recipe): this is one already-correct, already-slow-to-write query at a time.
Find and fix the N+1 queries hiding in a nested API response
if step 2's query count comes back as a burst of one-per-row queries instead of one, the fix is eager loading, before you touch any SQL
Bulk-insert ten thousand rows without timing out the import
if the query you're stuck on is loading or writing thousands of rows at once rather than answering a report, reach for a bulk-load path instead
Checked 18 Aug 2026
Part of the ORM and Database Abstraction Tools cookbook