Coding
AI Prompt for SQL-to-ORM Conversion
Convert raw SQL to ORM code with this AI prompt: idiomatic queries for your ORM, N+1 risks flagged, and guidance on what should stay raw SQL.
The prompt
Role: You are an ORM expert who translates SQL into clean, efficient ORM code — and knows when NOT to. Context: From: raw [DIALECT] SQL. To: [ORM] in [LANGUAGE]. Models: [MODEL_DEFINITIONS or 'infer from query']. SQL: [SQL_QUERY] Task: 1) Verdict first: should this query be ORM or stay raw? (Complex reporting queries often should stay raw — say so if true.) 2) If ORM: write the idiomatic [ORM] code with proper eager loading to avoid N+1. 3) Show the SQL the ORM generates (approximately) and compare with the original. 4) Flag N+1 risks, missing indexes the ORM version needs, and any query the ORM cannot express well. 5) If raw: show the parameterized raw-query version with proper result mapping. Format: Verdict first, then the ORM (or raw) code, then the generated-SQL comparison, then the risks. Constraints: Never introduce N+1 queries in the translation. Use parameterized queries — no string-interpolated SQL ever. Prefer the ORM's query builder over raw strings where expressive enough.
Variables to fill in
Replace each [variable] in the prompt with your own details:
[DIALECT] [ORM] [LANGUAGE] [MODEL_DEFINITIONS] [SQL_QUERY]
Example input
FROM=raw PostgreSQL SQL, TO=SQLAlchemy (Python), QUERY=complex join with aggregation for monthly revenue report, STYLE=ORM declarative
How to use this prompt
Paste the actual SQL — the translation needs the real query structure. Ask for the 'stay raw' verdict; ORMs are wrong for some queries.
Tips for the best results
- Take the 'stay raw' verdict seriously — fighting the ORM for reports wastes time.
- Ask for the generated SQL; ORMs surprise you with what they emit.
- Check eager loading explicitly — N+1 is the #1 ORM translation bug.
Frequently asked questions
Should everything become ORM?
It translates to ORM constructs and tells you honestly which queries should STAY raw — complex reports often should.
Does using an ORM mean I can forget SQL?
No — the prompt shows the SQL your ORM generates because you must read it. ORM fluency without SQL literacy produces N+1 disasters.