Queries
Queries are used to retrieve data from a database.
A query is a request for information from a database table or combination of tables. A query can be used to retrieve data from a single table or multiple tables. A query can also be used to insert, update, or delete data from a table.
Session
To execute a query you must first open a session. The examples on this page use
the async engine and session factory from the
overview, which reads async_db_url from
rxconfig.py:
import reflex as rx
from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
engine = create_async_engine(rx.config.get_config().async_db_url)
Session = async_sessionmaker(engine, expire_on_commit=False)async with Session() as session: closes the session when the code block is
finished. If session.commit() is not awaited, the changes will be rolled back
and not persisted to the database. The code can also explicitly roll back
without closing the session via await session.rollback().
Database calls in event handlers are always awaited through the async session.
A blocking call made with SQLAlchemy's sync Session would hold up every other
event the server is processing until the query returns.
The following example shows how to create a session and query the database.
First we create a table called User.
from sqlalchemy.orm import DeclarativeBase, Mapped, MappedAsDataclass, mapped_column
class Base(MappedAsDataclass, DeclarativeBase):
"""Base class for the app's tables."""
class User(Base):
__tablename__ = "user"
id: Mapped[int] = mapped_column(init=False, primary_key=True)
username: Mapped[str]
email: Mapped[str]Select
Then we create a session and query the User table. session.scalars() runs a
select() statement and returns the model instances.
from sqlalchemy import select
class QueryUser(rx.State):
name: str = ""
users: list[User] = []
@rx.event
async def get_users(self):
async with Session() as session:
result = await session.scalars(
select(User).where(User.username.contains(self.name))
)
self.users = result.all()The get_users method will query the database for all users that contain the
value of the state var name. Because User is a dataclass-mapped model, the
rows are serialized to the frontend and render with rx.foreach.
Insert
Similarly, the session.add() method adds a new record to the database. Adding
does not talk to the database, so it is not awaited; the commit is.
class AddUser(rx.State):
username: str = ""
email: str = ""
@rx.event
async def add_user(self):
async with Session() as session:
session.add(User(username=self.username, email=self.email))
await session.commit()Update
To update the user, first query the database for the object, make the desired modifications, and commit. The session tracks changes to objects it loaded, so there is no need to add the object again.
class ChangeEmail(rx.State):
username: str = ""
email: str = ""
@rx.event
async def modify_user(self):
async with Session() as session:
user = await session.scalar(
select(User).where(User.username == self.username)
)
if user is None:
return
user.email = self.email
await session.commit()session.scalar() returns the first column of the first row of the statement,
here the User itself, or None when nothing matches.
Delete
To delete a user, first query the database for the object, then delete it and commit.
class RemoveUser(rx.State):
username: str = ""
@rx.event
async def delete_user(self):
async with Session() as session:
user = await session.scalar(
select(User).where(User.username == self.username)
)
if user is None:
return
await session.delete(user)
await session.commit()ORM Object Lifecycle
The objects returned by queries belong to the session that created them. With
expire_on_commit=False on the session factory, their loaded columns stay
readable after the session closes, so they can be stored in state and rendered.
Columns the database fills in, such as the autogenerated primary key, are loaded
by the commit:
from typing import Any
class AddUserForm(rx.State):
user: User | None = None
@rx.event
async def add_user(self, form_data: dict[str, Any]):
async with Session() as session:
user = User(**form_data)
session.add(user)
await session.commit()
self.user = userNow the self.user object will have a correct reference to the autogenerated
primary key, id, even though this was not provided when the object was created
from the form data.
User(**form_data) passes every form field to the model's constructor, so the
form field names must match the model's columns. An extra field, such as an
input that has an id, raises a TypeError.
Only loaded attributes are available. An async session cannot load an attribute implicitly when it is read, so reading a relationship that was not eager-loaded raises an error, inside the session as well as after it closes. Eager-load the relationships the UI reads.
To modify an object stored in state in a new session, look it up again by primary
key with session.get() and change the fresh copy, then store that copy so the
state reflects what was written.
class AddUserForm(rx.State):
...
@rx.event
async def update_user(self, form_data: dict[str, Any]):
if self.user is None:
return
async with Session() as session:
user = await session.get(User, self.user.id)
if user is None:
return
for field, value in form_data.items():
setattr(user, field, value)
await session.commit()
self.user = userUsing SQL Directly
Avoiding SQL is one of the main benefits of using an ORM, but sometimes it is necessary for particularly complex queries, or when using database-specific features.
session.execute() runs a statement built with
sqlalchemy.text,
which allows colon-prefix names to be used as placeholders for bound parameters.
import sqlalchemy
import reflex as rx
class State(rx.State):
raw_user_tuples: list[list] = []
@rx.event
async def insert_user_raw(self, username: str, email: str):
async with Session() as session:
await session.execute(
sqlalchemy.text(
"INSERT INTO user (username, email) VALUES (:username, :email)"
),
{"username": username, "email": email},
)
await session.commit()
@rx.event
async def load_raw_users(self):
async with Session() as session:
result = await session.execute(sqlalchemy.text("SELECT * FROM user"))
self.raw_user_tuples = [list(row) for row in result.all()]ExpandCollapse
Load query results into state vars from event handlers, as here, rather than querying in a computed var: a computed var that reads no other state var is cached, so it would not see later writes to the database.
Writing Efficient Queries
Databases are generally much better at filtering, joining, and aggregating than Python. Every row returned by a query is sent over the network and held in memory as part of the state — for every user with an open session. Do the work in the query itself and return only display-ready results.
The examples below use a simple Order model.
class Order(Base):
__tablename__ = "order"
id: Mapped[int] = mapped_column(init=False, primary_key=True)
user_id: Mapped[int]
status: Mapped[str]
amount: Mapped[float | None] = mapped_column(default=None)Aggregate in SQL, not Python
Avoid fetching a whole table just to compute a summary in Python. Use the
database's aggregate functions (COUNT, SUM, AVG, MIN, MAX) with
GROUP BY so only the summary rows come back.
from sqlalchemy import func, select
class OrderStats(rx.State):
order_count: int = 0
orders_by_status: list[tuple[str, int]] = []
@rx.event
async def load_stats(self):
async with Session() as session:
# Count rows in the database instead of len() on a full fetch.
self.order_count = await session.scalar(select(func.count(Order.id)))
# One row per group, ready for a chart or summary table.
result = await session.execute(
select(Order.status, func.count(Order.id)).group_by(Order.status)
)
self.orders_by_status = [tuple(row) for row in result.all()]Related metrics can be computed in a single query with conditional aggregation, instead of issuing one query per metric:
import sqlalchemy
from sqlalchemy import func, select
class OrderKPIs(rx.State):
total_orders: int = 0
completed_orders: int = 0
total_amount: float = 0.0
@rx.event
async def load_kpis(self):
async with Session() as session:
result = await session.execute(
select(
func.count(Order.id),
func.sum(
sqlalchemy.case((Order.status == "completed", 1), else_=0)
),
func.coalesce(func.sum(Order.amount), 0.0),
)
)
total, completed, amount = result.one()
self.total_orders = total
self.completed_orders = completed or 0
self.total_amount = float(amount)ExpandCollapse
Avoid Queries Inside Loops
Issuing a query per item — the "N+1" pattern — multiplies network round trips.
Fetch everything in one statement with a JOIN, an IN (...) list, or
GROUP BY.
# Efficient: one query for all users at once.
async def load_orders(users: list[User]) -> list[Order]:
async with Session() as session:
result = await session.scalars(
select(Order).where(Order.user_id.in_([user.id for user in users]))
)
return list(result.all())
# Inefficient: one query per user (N+1).
async def load_orders_slowly(users: list[User]) -> list[Order]:
orders = []
async with Session() as session:
for user in users:
result = await session.scalars(
select(Order).where(Order.user_id == user.id)
)
orders.extend(result.all())
return ordersThe .in_() method binds each value as a separate query parameter, so it is
safe to use with user-provided values.
The example below binds the list with an expanding parameter:
import sqlalchemy
async def load_users_by_id(user_ids: list[int]) -> list:
async with Session() as session:
result = await session.execute(
sqlalchemy.text("SELECT * FROM user WHERE id IN :user_ids").bindparams(
sqlalchemy.bindparam("user_ids", expanding=True)
),
{"user_ids": user_ids},
)
return list(result.all())If the related objects are linked with foreign keys, the relationship loading techniques can also fetch linked objects without extra queries.
Return Only What the UI Needs
- Select only the columns the UI displays when tables are wide, instead of whole rows.
- Give every query that returns detail rows a
.limit(), and use offset-based pagination when the user needs more rows. - Load static data (dropdown options, date bounds) once in an
on_loadevent handler. When a filter changes, re-run only the filtered queries — not the option lookups. - Avoid caching large raw query results in state vars to work around a slow query: per-user state duplicates that data in server memory for every session. Fix the query instead — aggregate in SQL, add a limit, combine round trips. Keeping small, display-ready results in state (chart rows, KPI values, one page of a table) is the intended pattern.
Handling NULL Values
Database columns may contain NULL, which arrives in Python as None.
Aggregates like SUM and AVG also return NULL when they run over zero
rows. Casting such results directly will crash:
float(row[0]) # TypeError: float() argument must be ... not 'NoneType'There are two ways to handle this.
Coalesce in the Query (Preferred)
COALESCE returns its first non-NULL argument, so the query itself
guarantees a usable value. This is especially important for nullable numeric
columns and for aggregates that may run over empty groups.
from sqlalchemy import func, select
async def total_amount() -> float:
async with Session() as session:
return await session.scalar(select(func.coalesce(func.sum(Order.amount), 0.0)))The same works in raw SQL: SELECT COALESCE(SUM(amount), 0) FROM ....
Guard in Python
When consuming rows that may contain NULLs, fall back explicitly while
building the values:
orders = [
{
"status": str(row[0] or ""),
"amount": float(row[1]) if row[1] is not None else 0.0,
}
for row in rows
]Long Queries in Background Tasks
A regular event handler holds the state's lock until it returns, so other events
for the same user wait while a slow query runs. Run a long query in a
background task instead: it runs without the
lock, and takes it with async with self only to assign the result.
class ReportState(rx.State):
orders_by_status: list[tuple[str, int]] = []
loading: bool = False
@rx.event(background=True)
async def load_report(self):
async with self:
self.loading = True
async with Session() as session:
result = await session.execute(
select(Order.status, func.count(Order.id)).group_by(Order.status)
)
rows = [tuple(row) for row in result.all()]
async with self:
self.orders_by_status = rows
self.loading = False