Raw SQL
Raw SQL is a query you write as a string and send through a cursor, engine.execute, or Model.objects.raw. You own the SQL, the parameters, and the mapping back to Python.
Detailed Explanation
ORMs generate adequate SQL for "fetch this row by id". They generate painful SQL for a report with three CTEs and a window function. Raw SQL is how you write that report. It is also how you call INSERT ... ON CONFLICT when the ORM's upsert is incomplete.
The contract is: SQL string plus a parameter sequence or mapping. The driver interpolates placeholders safely. You never interpolate user text into the string. Identifiers (table names) cannot be bound as values; if you must make a table name dynamic, allowlist it against a set of known names.
Mapping rows is your job. fetchone() is a tuple. Set a row factory, use mappings(), or build a dataclass. Column order is not a stable API if you wrote SELECT *; name the columns.
Keep the SQL next to the Python that runs it, or in a .sql file you load, not scattered in views. Comment the why. A 40-line query without a name is a liability.
Transactions still apply. A raw UPDATE in a session that later rolls back should be part of that transaction. In SQLAlchemy, session.execute(text("...")) participates. A second connection you opened by hand does not.
EXPLAIN is how you check the plan. Raw SQL that worked on 1k rows can seq-scan 10M. Indexes are still your problem; the ORM was not going to invent them either.
Django's raw() returns model instances and has rules about primary keys. SQLAlchemy's text() is the Core hook. sqlite3 is the teaching tool.
Code Examples
import sqlite3
SQL = "select id, cents from orders where cents >= :min_cents"
with sqlite3.connect(":memory:") as conn:
conn.execute("create table orders (id text, cents int)")
conn.execute("insert into orders values ('11', 2500)")
conn.row_factory = sqlite3.Row
rows = conn.execute(SQL, {"min_cents": 1000}).fetchall()
print(rows[0]["id"], rows[0]["cents"]) # 11 2500from sqlalchemy import text
# session.execute(text("select id from orders where id = :id"), {"id": oid})Common Gotchas
f-string SQL
injection, and a broken cache of query plans. Bind parameters.
Dynamic table names from user input
cannot be bound. Allowlist.
Raw SQL on a second connection skips the ORM transaction
use the same session or connection.