In Room, when should a notes search whose tag, archived and text filters are chosen at runtime use @RawQuery, and what does it give up?
answer
- try one static query first
- escape hatch for runtime SQL
- no build-time verification
- read-only, must return a value
- bind with ?, never concatenate
basics
~10 sUse @RawQuery only when the statement's shape varies beyond what nullable :name parameters in one @Query can express. It gives up build-time verification, so mistakes fail at runtime, and it serves reads only.
solid answer
~40 sFirst try a static `@Query` with optional filters, such as `WHERE (:tag IS NULL OR tag = :tag)`, which keeps Room's build-time checks. Reach for `@RawQuery` when the statement's shape really varies, for example a variable set of clauses or a user-chosen sort column. The function takes the SQL as an object: `RoomRawQuery` in Room 3.0 (also in Room 2.x since 2.7.0), or `SupportSQLiteQuery` such as `SimpleSQLiteQuery` in Room 2.x on Android. Room still maps the rows into your return type, but it **cannot verify** the SQL, so a wrong column fails at runtime or gives an undefined result. The function must return a value, is for reads only, and needs `observedEntities` if it returns an observable type. Bind every user value with `?`; never splice it into the string.
code
kotlin · 37 linesimport androidx.room3.Dao
import androidx.room3.RawQuery
import androidx.room3.RoomRawQuery
@Dao
interface NoteSearchDao {
@RawQuery
suspend fun search(query: RoomRawQuery): List<Note>
}
suspend fun NoteSearchDao.searchNotes(
tag: String?,
includeArchived: Boolean,
text: String?,
): List<Note> {
val clauses = mutableListOf<String>()
val args = mutableListOf<String>()
if (tag != null) {
clauses += "tag = ?"
args += tag
}
if (!includeArchived) {
clauses += "archived = 0"
}
if (text != null) {
clauses += "(title LIKE ? OR body LIKE ?)"
args += "%$text%"
args += "%$text%"
}
val where = if (clauses.isEmpty()) "" else " WHERE " + clauses.joinToString(" AND ")
val sql = "SELECT * FROM notes$where ORDER BY title"
return search(
RoomRawQuery(sql) { statement ->
args.forEachIndexed { index, value -> statement.bindText(index + 1, value) }
}
)
}go deeper
Know that @RawQuery runs SQL built at runtime, that Room cannot check it at build time, and that user values must be bound, not concatenated.
Show the static alternative with nullable :name filters, the RoomRawQuery and SimpleSQLiteQuery forms, and the read-only, must-return-a-value rules.
Decide when the shape truly varies, allow-list identifiers, list observedEntities for observable results, and replace lost compile checks with tests over every clause.
Keep raw SQL rare and centralised behind one reviewed builder, so the build-time verification that justifies Room still covers almost every query.
## The problem A notes app's search screen lets the user filter by tag, include or exclude archived notes, and search titles and bodies for text, in any combination. Each `@Query` is a fixed string checked at build time, so the question is whether one fixed string can cover every combination, or whether the SQL has to be assembled at runtime. ## First choice: one static query with optional filters Often a single query does the job, because a bound parameter can switch its own condition off: ```kotlin @Query( """ SELECT * FROM notes WHERE (:tag IS NULL OR tag = :tag) AND (:includeArchived OR archived = 0) AND (:text IS NULL OR title LIKE '%' || :text || '%') ORDER BY title """ ) suspend fun search(tag: String?, includeArchived: Boolean, text: String?): List<Note> ``` This keeps everything Room offers: the SQL is verified against the schema at build time, parameters are bound by name, and the mapping is generated knowing exactly which columns come back. For a handful of optional filters, this is the version to write. A variable-length list on its own does not need raw SQL either: `tag IN (:tags)` binds a whole collection inside a static, verified query. ## When @RawQuery earns its place `@RawQuery` is Room's documented **escape hatch**: you build the SQL at runtime, and Room still converts the result rows into objects. It fits when the statement's *shape* changes: - a variable set of conditions, where each filter the user turns on adds its own clause, or a join, to the statement; - a sort column or direction the user picks, which SQL cannot take as a bound parameter; - queries assembled by a filter builder shared across several screens. The function declares one parameter carrying the SQL and its bindings: | Major | Parameter type | Binding | |---|---|---| | Room 3.0 | `RoomRawQuery(sql, onBindStatement)` | a lambda calling `bindText`, `bindLong` and the like on the `SQLiteStatement` | | Room 2.x on Android | `SupportSQLiteQuery`, usually `SimpleSQLiteQuery(query, bindArgs)` | an array of arguments | | Room 2.x since 2.7.0, including multiplatform code | `RoomRawQuery` | the same binding lambda as in 3.0 | `RoomRawQuery` arrived in Room 2.7.0 so raw queries could work in multiplatform code, and it is the type Room 3.0's own documentation uses. Placeholders inside the raw SQL are positional `?` marks, bound by index starting at 1. ## What you give up 1. **Build-time verification.** Room cannot see the SQL, so a misspelt column or a syntax error surfaces only when the query runs, as a runtime failure or an undefined result. 2. **Some efficiency.** With `@Query` Room knows the result columns at compile time; for a raw query the generated mapping must allow for columns that may be missing. 3. **Writes.** `@RawQuery` functions are for reads. Room documents write statements through them as undefined behaviour and points writes at the database's connection APIs instead (`useWriterConnection` in Room 3.0). 4. **A `Unit` return.** A raw query function must return a value. 5. **Automatic observation.** If it returns an observable type, you must list the tables it reads in `observedEntities`, because Room cannot work them out from SQL it never sees. ## Building the SQL safely The assembled string is the dangerous part. The rules: - Every **value** that came from the user (tag, search text, ids) goes through a `?` placeholder and a bind call, never string concatenation. Binding keeps a quote in the search text from rewriting the statement, so it cannot inject SQL. - Every **identifier** the user influences (the sort column, `ASC` or `DESC`) comes from a fixed allow-list in code, because identifiers cannot be bound. - Keep the builder in one place and cover it with tests that run each filter combination against a real in-memory database, since the compiler no longer checks it. ## A senior's checklist before merging a @RawQuery - Could one static `@Query` with nullable parameters do this? If so, use it. - Are all user values bound, and all identifiers allow-listed? - Is the function read-only and returning a value? - If it returns an observable type, are its tables listed in `observedEntities`? - Do tests cover every clause the builder can emit?
- Your @RawQuery returns a Flow<List<Note>> but never re-emits after a note is inserted; why?Room cannot read the table names out of SQL it only sees at runtime, so it does not know which tables to watch. Declare them with `@RawQuery(observedEntities = [Note::class])`; Room then invalidates the query when the notes table changes. How the re-emission itself works belongs with Room's coroutine support.
- How do you let the user sort by title or by last edit time without opening an injection hole?Map the user's choice to a column name from a fixed list in code, for example a `when` over a sort enum returning `"title"` or `"updated_at"`, and append only that constant. Identifiers cannot be bound with `?`, so the allow-list is the protection; user text never reaches the ORDER BY clause.
- Room still verifies a @RawQuery's SQL at build time, just with weaker checks.
- @RawQuery is the normal way to run dynamic UPDATE and DELETE statements.
- Concatenating the search text into the SQL is fine because Room escapes it.
- A @RawQuery returning Flow re-emits on any table change without extra configuration.
- Any query with an optional filter needs @RawQuery.
Assumes Room 3.0, where @RawQuery is built around RoomRawQuery; Room 2.x on Android also takes SupportSQLiteQuery, and has accepted RoomRawQuery since 2.7.0.