Queries in 2.0 Style, and When to Write SQL Yourself
Build select, insert, update and delete statements in SQLAlchemy 2.0 style, then drop to parameterised raw SQL with text() for a report query — and see why the two forms are not interchangeable.
Contentsand lesson path
On this page
- The task
- Step 1: select, build then execute
- Step 2: insert, update, delete as statements
- Step 3: the report stays in SQL
- Step 4: why parameters are not formatting
- 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. The task
The reading-list API needs data operations: list the longest books, add a book, correct a page count, retire a record. In SQLAlchemy 2.0 style each of those is a statement object built first and executed after, through a session — the same select() you met when choosing a level, now for writes as well as reads.
Then the task turns to something the ORM models from the previous lesson handle badly: a report that ranks authors by how many substantial books they have. It is one aggregation over joined tables — work PostgreSQL is built for — so it stays in SQL, wrapped in text() with values arriving as bound parameters.
The examples run against the same lab PostgreSQL on port 55433, with the authors and books tables from the models lesson seeded afresh: three Le Guin books and two Herbert books, so the first free book id is 6. Open seed.py from the models lesson, replace its two Author(...) definitions with the ones below, and run it once more before you start; it drops and recreates both tables, so the ids start from 1 again.
le_guin = Author(
name="Ursula K. Le Guin",
books=[
Book(title="The Left Hand of Darkness", pages=304),
Book(title="The Dispossessed", subtitle="An Ambiguous Utopia", pages=346),
Book(title="A Wizard of Earthsea", pages=183),
],
)
herbert = Author(
name="Frank Herbert",
books=[Book(title="Dune", pages=412), Book(title="Dune Messiah", pages=256)],
)Frank Herbert -> ['Dune', 'Dune Messiah']
Ursula K. Le Guin -> ['The Left Hand of Darkness', 'The Dispossessed',
'A Wizard of Earthsea']02. Step 1: select, build then execute
A select() builds a statement; nothing runs until a session executes it. Chain where() for conditions, order_by() for ordering, limit() for paging. session.execute(stmt) returns rows; when the statement selects whole ORM entities, session.scalars(stmt) unwraps them into the objects themselves.
from sqlalchemy import create_engine, select
from sqlalchemy.orm import Session
from models import Author, Base, Book
engine = create_engine(
"postgresql+psycopg://postgres:lab@localhost:55433/lab"
)
stmt = (
select(Book.title, Book.pages)
.where(Book.pages > 200)
.order_by(Book.pages.desc())
.limit(3)
)
with Session(engine) as session:
for title, pages in session.execute(stmt).all():
print(f"{pages:>4} {title}") 412 Dune
346 The Dispossessed
304 The Left Hand of DarknessBecause select(Book.title, Book.pages) names columns, each row is a tuple-like Row you unpack. Selecting Book instead would give whole entities, and scalars() the objects. Statements are plain values: build one, print it to see the SQL, pass it to a helper, or add a clause conditionally before executing.
03. Step 2: insert, update, delete as statements
Writes use the same shape. insert(), update() and delete() are statement factories from sqlalchemy; .values() sets what to write, .where() decides which rows, and executing them through a session opens a transaction that ends at your commit(). Add .returning() and the executed statement hands back columns of the affected rows — PostgreSQL computes them, so a SERIAL id or a server_default timestamp is there without a second query.
from sqlalchemy import create_engine, delete, insert, update
from sqlalchemy.orm import Session
from models import Book
engine = create_engine(
"postgresql+psycopg://postgres:lab@localhost:55433/lab"
)
with Session(engine) as session:
row = session.execute(
insert(Book)
.values(title="The Telling", pages=253, author_id=1)
.returning(Book.id, Book.title)
).one()
session.commit()
print("inserted:", row.title, "with id", row.id)
result = session.execute(
update(Book).where(Book.title == "Dune Messiah").values(pages=255)
)
session.commit()
print("updated rows:", result.rowcount)
result = session.execute(delete(Book).where(Book.pages < 200))
session.commit()
print("deleted rows:", result.rowcount)inserted: The Telling with id 6
updated rows: 1
deleted rows: 1Statement writes and the session's object tracking are two routes into the same unit of work. When you already hold the objects — load a book, change book.pages, commit() — the session flushes an UPDATE for the changed columns. When you do not want to load anything — "raise the page count of every book by this publisher" — a statement does the job in one round trip. rowcount comes from the database: it is how many rows the WHERE clause matched.
One habit to keep: the session opens a transaction on first use and holds it until commit() or rollback(). Executing a write and forgetting the commit leaves the transaction to roll back when the session closes — silent on your side, locked rows on the database's.
04. Step 3: the report stays in SQL
Now the report: authors with at least two books of at least 250 pages, most books first. It joins, groups, filters groups and orders — the shape you learned in the SQL lessons. Rebuilding it from ORM objects would mean loading every book into Python to count them; text() lets the finished SQL run as written, with a colon name for every value that changes between calls.
from sqlalchemy import create_engine, text
from sqlalchemy.orm import Session
engine = create_engine(
"postgresql+psycopg://postgres:lab@localhost:55433/lab"
)
REPORT = text(
"""
SELECT a.name AS author,
COUNT(b.id) AS books,
COALESCE(SUM(b.pages), 0) AS total_pages
FROM authors a
JOIN books b ON b.author_id = a.id
GROUP BY a.id, a.name
HAVING COUNT(*) FILTER (WHERE b.pages >= :min_pages) >= :min_books
ORDER BY books DESC, a.name
"""
)
with Session(engine) as session:
for row in session.execute(REPORT, {"min_pages": 250, "min_books": 2}):
print(f"{row.author:<20} {row.books:>2} books {row.total_pages:>4} pages")Ursula K. Le Guin 3 books 903 pages
Frank Herbert 2 books 667 pagesThe two colon names — :min_pages and :min_books — are bound parameters. The values travel in a separate dictionary, and the same statement runs for any cutoffs: tomorrow's call passes {"min_pages": 150, "min_books": 1} and the SQL text does not change, which also means the database can reuse its compiled plan. Rows come back as Row objects, so row.author is the column aliased in the SQL — no model class is involved, and none is needed.
05. Step 4: why parameters are not formatting
A search feature takes a title fragment from a request. One version glues the fragment into the SQL string; the other binds it. A user sends the fragment ' OR '1'='1 — not an attack yet, just awkward input.
from sqlalchemy import create_engine, text
engine = create_engine(
"postgresql+psycopg://postgres:lab@localhost:55433/lab"
)
needle = "' OR '1'='1"
fstring_sql = f"SELECT id FROM books WHERE title LIKE '%{needle}%'"
bound_sql = "SELECT id FROM books WHERE title LIKE :pattern"
with engine.connect() as conn:
injected = len(conn.execute(text(fstring_sql)).all())
bound = len(
conn.execute(text(bound_sql), {"pattern": f"%{needle}%"}).all()
)
print(f"f-string matches {injected} rows, bound parameter matches {bound}")f-string matches 5 rows, bound parameter matches 0The interpolated string stopped being the query you meant: it now ends in ... LIKE '%' OR '1'='1%' — a condition that is true for nearly every row, so five rows came back where the honest match is none. The bound parameter searched for the literal text and matched nothing, which is the correct answer to that input. text() escapes nothing and forbids nothing; safety comes entirely from keeping values out of the SQL text. Note also that plain strings are not accepted by execute() in 2.0 — the f-string version above only runs because it is wrapped in text(), which is exactly the moment to notice what the string contains.
06. Check your understanding
07. Apply it
Write the report endpoint from this skill's practice as it would appear in a service: a text() statement with bound parameters for the cutoffs, executed through a session, rows converted to response dictionaries. Then add a query-string parameter for min_books and check that the SQL never changes — only the dictionary does. Finish by writing the same report with select() and func.count and decide, in one paragraph, which version you would keep and why.
08. Review prompt
Without looking back: how do you build a filtered, ordered, limited read in 2.0 style, and what does scalars() give you that execute() does not? What does rowcount tell you after an UPDATE? Name two kinds of query that belong in text() rather than select(). Finally, explain in two sentences why a bound parameter cannot change the structure of a query while an f-string can.
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.