ORM, Query Builder or Raw SQL: Choosing the Level
See the same question answered at three levels of abstraction — raw SQL, a query builder and an ORM — and learn when each level is the right tool.
Contentsand lesson path
On this page
- Why it matters
- The same question at three levels
- SQLAlchemy: two layers, one style
- Choosing a level
- Check your understanding
- Apply it
- Review prompt
Lessons of Data Access with SQLAlchemy
- ORM, Query Builder or Raw SQL: Choosing the Level Concept · 15 min
- Typed Models and Relationships Worked example · 25 min
- Queries in 2.0 Style, and When to Write SQL Yourself Worked example · 25 min
- Lab: Hunting an N+1 in the SQL Log Lab · 25 min
- Sessions, Pools and Async Engines in a Web App Concept · 25 min
- Check: Read the ORM Code, Predict the SQL Knowledge check · 8 questions
What you will learn
- Write select, insert, update and delete operations in 2.0 style, and use parameterized raw SQL through text() when the ORM is the wrong tool.
Prerequisites: SQL Fundamentals
01. Why it matters
The reading-list API you built in the FastAPI lab keeps its books in a Python dictionary. That store dies with the process, cannot be shared between two workers, and cannot answer questions like "which author has the most books?" without loading everything. PostgreSQL fixes all of that, and you already speak its language from the SQL skill.
What is new is the level at which your Python code talks to the database. Every database access you will ever write sits somewhere between two extremes: a hand-written SQL string sent to the driver, or a plain Python object that happens to be backed by a row. Pick the wrong level and you either fight the tool — formatting SQL strings by hand for routine reads — or you leak the database everywhere, with ORM objects passed through places that should only know HTTP.
This lesson makes the levels concrete with one small question asked three ways, so that later lessons can use each level without ceremony.
02. The same question at three levels
The question: which titles have more than 300 pages, longest first? The database is SQLite here so the sample runs anywhere; the levels look the same against PostgreSQL.
Level 1 — the DBAPI, raw SQL. sqlite3 and psycopg implement the Python Database API (DBAPI, PEP 249): you open a connection, send SQL text, and get rows back as tuples by default. asyncpg gives the same level of control through its own async API, which is not a DBAPI and returns Record objects; SQLAlchemy wraps it in a DBAPI-style adapter. You are in full control and fully on your own: the SQL is a string, the values are separate parameters, and the rows are untyped.
import sqlite3
with sqlite3.connect("l01.db") as conn:
conn.execute("DROP TABLE IF EXISTS books")
conn.execute(
"CREATE TABLE books (id INTEGER PRIMARY KEY, title TEXT, pages INTEGER)"
)
conn.executemany(
"INSERT INTO books (title, pages) VALUES (?, ?)",
[("The Left Hand of Darkness", 304), ("Dune", 412),
("The Dispossessed", 346), ("A Wizard of Earthsea", 183)],
)
conn.commit()
dbapi_rows = conn.execute(
"SELECT title, pages FROM books WHERE pages > ? ORDER BY pages DESC",
(300,),
).fetchall()
print("dbapi:", dbapi_rows)Level 2 — a query builder. Instead of a string, you describe the statement with Python objects: tables as Table objects, conditions as expressions. The library compiles them into SQL for your database and keeps parameters separate. You still think in rows and columns, but the compiler handles quoting, keyword differences and escaping.
from sqlalchemy import (
Column, Integer, MetaData, String, Table, create_engine, select,
)
engine = create_engine("sqlite:///l01.db")
metadata = MetaData()
books = Table(
"books",
metadata,
Column("id", Integer, primary_key=True),
Column("title", String(200)),
Column("pages", Integer),
)
stmt = (
select(books.c.title, books.c.pages)
.where(books.c.pages > 300)
.order_by(books.c.pages.desc())
)
print("core SQL:", stmt)
with engine.connect() as conn:
core_rows = conn.execute(stmt).all()
print("core: ", core_rows)Level 3 — the ORM. A class describes each table, and queries return instances of that class. Attributes are typed, relationships between tables become Python references, and a session tracks changes for you. The price is a layer with rules of its own, which the rest of this skill teaches.
from sqlalchemy.orm import DeclarativeBase, Mapped, Session, mapped_column
class Base(DeclarativeBase):
pass
class Book(Base):
__tablename__ = "books"
id: Mapped[int] = mapped_column(primary_key=True)
title: Mapped[str]
pages: Mapped[int]
with Session(engine) as session:
orm_books = session.scalars(
select(Book).where(Book.pages > 300).order_by(Book.pages.desc())
).all()
print("orm: ", [(b.title, b.pages) for b in orm_books])dbapi: [('Dune', 412), ('The Dispossessed', 346), ('The Left Hand of Darkness', 304)]
core SQL: SELECT books.title, books.pages
FROM books
WHERE books.pages > :pages_1 ORDER BY books.pages DESC
core: [('Dune', 412), ('The Dispossessed', 346), ('The Left Hand of Darkness', 304)]
orm: [('Dune', 412), ('The Dispossessed', 346), ('The Left Hand of Darkness', 304)]Three levels, one answer. Notice what the query builder printed: the statement object is SQL waiting to happen — :pages_1 is a bound parameter, not a number glued into the string. And notice that the ORM query goes through session.scalars() rather than execute(): a session executes statements and hands back objects, one per row, instead of row tuples.
03. SQLAlchemy: two layers, one style
SQLAlchemy is not one thing but two. Core is the engine, connections, pooling and the SQL expression language you met at level 2. The ORM sits on top of Core: it maps classes to tables, tracks objects in a session, and writes the changes back as SQL — always through Core. When the ORM runs your select(Book), the statement that reaches PostgreSQL is a Core statement.
Since version 2.0 the two layers share one style: you build a select() statement and execute it, whether you want rows or objects. The old split — session.query() for the ORM, something else for Core — is legacy. The 2.0 style is what this skill and the official unified tutorial teach, and it is why mixing levels in one code base is unremarkable: a service can use the ORM for its day-to-day reads and drop to text() for a report, in the same transaction.
04. Choosing a level
The choice is per query, not per project. A practical ordering:
- Start with the ORM for anything that touches rows your application models: create, read, update and delete of business entities. Typed objects, relationship loading and change tracking save the most code exactly here, and the next lessons show how.
- Drop to
text()— raw SQL with bound parameters — when the database is the right place for the work. Reporting queries, aggregations, window functions, recursive CTEs, bulk upserts withON CONFLICT: SQL that already exists from a psql session belongs intext()verbatim rather than being rebuilt in objects "for consistency". The lesson on 2.0-style queries shows the boundary. - Use the query builder directly when you compose SQL programmatically but do not want ORM objects back — dynamic filters from a search box, or writing to tables that have no model class.
Two more factors weigh in. Portability: ORM and query-builder statements compile per dialect, so the same code runs on PostgreSQL in production and SQLite in tests; a dialect-specific text() query ties that code to one database. And auditability: whatever the level, the SQL that runs can always be logged — the N+1 lab later in this skill reads exactly that log.
What you should not do is pick a level for performance reasons by default. All three levels send SQL to the same engine; the ORM adds bookkeeping in Python, not a different query plan. Where the ORM genuinely costs you — loading ten thousand objects to compute one number — the fix is usually to change what you ask for, and that is a signal to move that query down a level.
05. Check your understanding
06. Apply it
Take the five reading-list routes from the FastAPI lab — create, list, get, replace, delete — plus the report endpoint this skill's practice adds. For each one, write one line: which level (ORM, query builder or text()) you would use and why. You should find four or five lines say "ORM", and the report says text() — that mix is the normal shape of a service, and the next two lessons implement exactly those two halves.
07. Review prompt
Without looking back: name the three levels and say in one sentence each what you gain and what you give up. What does the ORM add on top of the query builder? Give two signals that a query should be written as raw SQL through text() rather than rebuilt with models. Finally, what does :pages_1 in a compiled statement mean, and why is that safer than the same number appearing inside the SQL string?
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.