SQLAlchemy 2.0: Use select() with Session.execute() for New ORM Code
New SQLAlchemy 2.x code should use select() with Session.execute() instead of the legacy Query API. This guide shows the smallest safe design, operational checks, and failure modes.
05 Aug 2025, 10:04 UTC

Problem and takeaway
If you are writing new application code on SQLAlchemy 2.x, avoid starting from legacy Session.query() examples. The Query API still functions in 2.x, but it is in maintenance mode and can emit deprecation warnings. The forward-compatible pattern is to build a select() construct and pass it to Session.execute(). This style unifies Core and ORM execution, works for reads, counts, existence checks, and DML, and is the default choice for new code.
Requirements
- SQLAlchemy 2.0 or newer installed.
- ORM-mapped classes, typically declared with SQLAlchemy’s declarative base.
- A database driver for your dialect, such as psycopg2 for PostgreSQL.
- A
Sessionfor synchronous code or anAsyncSessionfor asynchronous code.
Session is a short-lived unit of work. It should be opened for a request or transaction and closed when that work finishes. select() is a Core construct that SQLAlchemy 2.0 reuses for ORM queries, so the same statement pattern can later be reused for counts or insert(), update(), and delete() operations.
Smallest suitable design
Assume a mapped User class with an id column. The following is a complete read path in synchronous code:
from sqlalchemy import create_engine, select
from sqlalchemy.orm import Session
engine = create_engine("", echo=True)
with Session(engine) as session:
stmt = select(User).where(User.id == 1)
user = session.execute(stmt).scalars().first()
select(User).where(User.id == 1) builds the statement. session.execute(stmt) runs it against the database. Because the statement selects whole ORM entities, .scalars() unwraps the result so .first() returns a mapped User instance or None. Without scalars(), the result is a Row object, and attribute access such as user.name can fail or behave unexpectedly.
To load a relationship and avoid an N+1 query—where one query triggers many additional queries for related rows—pass a loading option to the same select():
from sqlalchemy.orm import joinedload
stmt = select(User).options(joinedload(User.addresses)).where(User.id == 1)
user = session.execute(stmt).scalars().first()
Trust and data boundaries
- Session boundary. Do not pass a session across threads or keep it open beyond the request that created it. Use a context manager (
with Session(engine) as session:) so it closes deterministically. - Parameter boundary. Expressions such as
User.id == user_iduse bound parameters. Never build thewhereclause by interpolating user input into a string. If you need raw SQL, usetext()with explicit bind parameters. - Async boundary. Synchronous
Session.execute()blocks the calling thread. In an async application, useAsyncSessionandawait session.execute(stmt); do not mix sync session calls into an async event loop.
Operational checks
- Confirm the installed version. Run this in your project’s virtual environment:
Expected output: a version string starting withpython -c "import sqlalchemy; print(sqlalchemy.__version__)"2.. If it starts with1., theselect()ORM execution pattern is not supported and you must upgrade first. - Inspect emitted SQL. Set
echo=Trueon the engine, as shown above, and confirm the SQL contains the intendedWHEREclause and column list. - Verify the return type. Execute a known query in a test session and assert that the result is a mapped instance or
None, not aRow. - Compare against legacy behavior. In staging, run the equivalent
Session.query()call and theselect()call against the same data and compare row counts or query plans. This catches behavioral drift during migration.
Failure modes and conditions
- Missing
scalars(). Callingsession.execute(stmt).first()withoutscalars()returns aRow. Code that then accessesrow.Useror assumes direct attribute access will break. - Sync session in async code. Blocking
Session.execute()inside an async handler degrades responsiveness and can timeout under load. - No relationship loading. Accessing
user.addresseswithoutjoinedload()orselectinload()triggers a separate query per parent row in a loop. - Legacy Query composition. Some string-based joins or dynamic
Queryobject composition do not have one-to-oneselect()equivalents and may require a rewrite.
Conditions that change the design
- If the application is async (for example, FastAPI or asyncio-based), replace
SessionwithAsyncSessionandawaiteveryexecute()call. - If the workload is mostly ad-hoc reporting with dynamic string joins, plain Core table objects may be simpler than ORM-mapped
select()statements. - If the environment is still on SQLAlchemy 1.4, adopt
select()only after upgrading to 2.0.
Write operations
The same select() execution style extends to writes through insert(), update(), and delete(). Unlike the read examples above, write operations change state, so wrap them in a transaction and call session.commit() to persist, or session.rollback() to discard on failure.
Practical verification
After deploying the pattern, enable echo=True in a staging environment and review the generated SQL for the expected WHERE clause and bound parameters. Then run a read path that loads a relationship and confirm with database logs or query statistics that only the expected number of queries executed. If you see one query per row, add joinedload() or selectinload() to the select() statement.