For AI agents: the complete documentation index is at llms.txt. Markdown versions are available by appending .md or sending Accept: text/markdown.
Reflex Logo
Docs Logo
Database

/

Queries

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 create a rx.session. You can use the session to query the database using SQLModel or SQLAlchemy syntax.

The rx.session statement will automatically close the session when the code block is finished. If session.commit() is not called, the changes will be rolled back and not persisted to the database. The code can also explicitly rollback without closing the session via session.rollback().

The following example shows how to create a session and query the database. First we create a table called User.

Select

Then we create a session and query the User table.

The get_users method will query the database for all users that contain the value of the state var name.

Insert

Similarly, the session.add() method to add a new record to the database or persist an existing object.

Update

To update the user, first query the database for the object, make the desired modifications, .add the object to the session and finally call .commit().

Delete

To delete a user, first query the database for the object, then call .delete() on the session and finally call .commit().

ORM Object Lifecycle

The objects returned by queries are bound to the session that created them, and cannot generally be used outside that session. After adding or updating an object, not all fields are automatically updated, so accessing certain attributes may trigger additional queries to refresh the object.

To avoid this, the session.refresh() method can be used to update the object explicitly and ensure all fields are up to date before exiting the session.

Now 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.

If self.user needs to be modified or used in another query in a new session, it must be added to the session. Adding an object to a session does not necessarily create the object, but rather associates it with a session where it may either be created or updated accordingly.

If an ORM object will be referenced and accessed outside of a session, you should call .refresh() on it to avoid stale object exceptions.

Using 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.

SQLModel exposes the session.execute() method that can be used to execute raw SQL strings. If parameter binding is needed, the query may be wrapped in , which allows colon-prefix names to be used as placeholders.

Never use string formatting to construct SQL queries, as this may lead to SQL injection vulnerabilities in the app.
Expand

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.

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.

Related metrics can be computed in a single query with conditional aggregation, instead of issuing one query per metric:

Expand

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.

The .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:

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_load event 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:

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.

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:

Async Database Operations

Reflex provides an async version of the session function called rx.asession for asynchronous database operations. This is useful when you need to perform database operations in an async context, such as within async event handlers.

Configuring the Async Database URL

rx.asession needs its own async_db_url in rxconfig.py. It must point at the same database as db_url but use an async driver. Calling rx.asession() when it is unset raises an error.

The matching async DBAPI driver is not part of the reflex[db] extra, so install it separately. For the SQLite URL above, install aiosqlite:

For PostgreSQL, install psycopg (psycopg3). It works as both the sync and async driver, so db_url and async_db_url can share one postgresql+psycopg://... scheme:

The rx.asession function returns an async SQLAlchemy session that must be used with an async context manager. Most operations against the asession must be awaited.

Async Select

The following example shows how to query the database asynchronously:

Async Insert

To add a new record to the database asynchronously:

Async Update

To update a user asynchronously:

Async Delete

To delete a user asynchronously:

Async Refresh

Similar to the regular session, you can refresh an object to ensure all fields are up to date:

Async SQL Execution

You can also execute raw SQL asynchronously:

Built with Reflex