public
abstract
@interface
Query
implements
Annotation
android.arch.persistence.room.Query
Marks a method in a Dao annotated class as a query method.
The value of the annotation includes the query that will be run when this method is called. This
query is verified at compile time by Room to ensure that it compiles fine against the
database.
The arguments of the method will be bound to the bind arguments in the SQL statement. See
SQLite's binding documentation> for
details of bind arguments in SQLite.
Room only supports named bind parameter :name to avoid any confusion between the
method parameters and the query bind parameters.
Room will automatically bind the parameters of the method into the bind arguments. This is done
by matching the name of the parameters to the name of the bind arguments.
@Query("SELECT * FROM user WHERE user_name LIKE :name AND last_name LIKE :last")
public abstract List<User> findUsersByNameAndLastName(String name, String last);
As an extension over SQLite bind arguments, Room supports binding a list of parameters to the
query. At runtime, Room will build the correct query to have matching number of bind arguments
depending on the number of items in the method parameter.
@Query("SELECT * FROM user WHERE uid IN(:userIds)")
public abstract List findByIds(int[] userIds);
For the example above, if the userIds is an array of 3 elements, Room will run the
query as: SELECT * FROM user WHERE uid IN(?, ?, ?) and bind each item in the
userIds array into the statement.
There are 3 types of queries supported in Query methods: SELECT, UPDATE and DELETE.
For SELECT queries, Room will infer the result contents from the method's return type and
generate the code that will automatically convert the query result into the method's return
type. For single result queries, the return type can be any java object. For queries that return
multiple values, you can use List or Array. In addition to these, any
query may return Cursor or any query result can be wrapped in
a LiveData.
RxJava2 If you are using RxJava2, you can also return Flowable<T> or
Publisher<T> from query methods. Since Reactive Streams does not allow null, if
the query returns a nullable type, it will not dispatch anything if the value is null
(like fetching an Entity row that does not exist).
You can return Flowable<T[]> or Flowable<List<T>> to workaround this limitation.
Both Flowable<T> and Publisher<T> will observe the database for changes and
re-dispatch if data changes. If you want to query the database without observing changes, you can
use Maybe<T> or Single<T>. If a Single<T> query returns null,
Room will throw
EmptyResultSetException.
UPDATE or DELETE queries can return void or int. If it is an int,
the value is the number of rows affected by this query.
You can return arbitrary POJOs from your query methods as long as the fields of the POJO match
the column names in the query result.
For example, if you have class:
class UserName {
public String name;
@ColumnInfo(name = "last_name")
public String lastName;
}
You can write a query like this:
@Query("SELECT last_name, name FROM user WHERE uid = :userId LIMIT 1")
public abstract UserName findOneUserName(int userId);
And Room will create the correct implementation to convert the query result into a
UserName object. If there is a mismatch between the query result and the fields of the
POJO, as long as there is at least 1 field match, Room prints a
CURSOR_MISMATCH warning and sets as many fields as it can.
Content and code samples on this page are subject to the licenses described in the Content License. Java and OpenJDK are trademarks or registered trademarks of Oracle and/or its affiliates.
Last updated 2025-02-10 UTC.
[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Missing the information I need","missingTheInformationINeed","thumb-down"],["Too complicated / too many steps","tooComplicatedTooManySteps","thumb-down"],["Out of date","outOfDate","thumb-down"],["Samples / code issue","samplesCodeIssue","thumb-down"],["Other","otherDown","thumb-down"]],["Last updated 2025-02-10 UTC."],[],[],null,["# Query\n\nSummary: [Methods](#pubmethods) \\| [Inherited Methods](#inhmethods) \n\nQuery\n=====\n\n| The `android.arch` Architecture Components packages are no longer maintained. They have been superseded by the corresponding [androidx.\\*](/jetpack/androidx/migrate) packages. See [androidx.room.Query](/reference/androidx/room/Query) instead.\n\n\n`\npublic\n\n\nabstract\n@interface\nQuery\n`\n\n\n`\n\n\nimplements\n\nAnnotation\n\n\n`\n\n|-------------------------------------|\n| android.arch.persistence.room.Query |\n\n\u003cbr /\u003e\n\n*** ** * ** ***\n\nMarks a method in a [Dao](/reference/android/arch/persistence/room/Dao) annotated class as a query method.\n\n\nThe value of the annotation includes the query that will be run when this method is called. This\nquery is **verified at compile time** by Room to ensure that it compiles fine against the\ndatabase.\n\n\nThe arguments of the method will be bound to the bind arguments in the SQL statement. See\nSQLite's binding documentation for details of bind arguments in SQLite.\n\n\nRoom only supports named bind parameter `:name` to avoid any confusion between the\nmethod parameters and the query bind parameters.\n\n\nRoom will automatically bind the parameters of the method into the bind arguments. This is done\nby matching the name of the parameters to the name of the bind arguments. \n\n```\n @Query(\"SELECT * FROM user WHERE user_name LIKE :name AND last_name LIKE :last\")\n public abstract List\u003cUser\u003e findUsersByNameAndLastName(String name, String last);\n \n```\n\n\nAs an extension over SQLite bind arguments, Room supports binding a list of parameters to the\nquery. At runtime, Room will build the correct query to have matching number of bind arguments\ndepending on the number of items in the method parameter. \n\n```\n @Query(\"SELECT * FROM user WHERE uid IN(:userIds)\")\n public abstract List findByIds(int[] userIds);\n \n```\nFor the example above, if the `userIds` is an array of 3 elements, Room will run the query as: `SELECT * FROM user WHERE uid IN(?, ?, ?)` and bind each item in the `userIds` array into the statement.\n\n\nThere are 3 types of queries supported in `Query` methods: SELECT, UPDATE and DELETE.\n\n\nFor SELECT queries, Room will infer the result contents from the method's return type and\ngenerate the code that will automatically convert the query result into the method's return\ntype. For single result queries, the return type can be any java object. For queries that return\nmultiple values, you can use [List](/reference/java/util/List) or `Array`. In addition to these, any\nquery may return [Cursor](https://developer.android.com/reference/android/database/Cursor.html) or any query result can be wrapped in\na [LiveData](/reference/android/arch/lifecycle/LiveData).\n\n\n**RxJava2** If you are using RxJava2, you can also return `Flowable\u003cT\u003e` or\n`Publisher\u003cT\u003e` from query methods. Since Reactive Streams does not allow `null`, if\nthe query returns a nullable type, it will not dispatch anything if the value is `null`\n(like fetching an [Entity](/reference/android/arch/persistence/room/Entity) row that does not exist).\nYou can return `Flowable\u003cT[]\u003e` or `Flowable\u003cList\u003cT\u003e\u003e` to workaround this limitation.\n\n\nBoth `Flowable\u003cT\u003e` and `Publisher\u003cT\u003e` will observe the database for changes and\nre-dispatch if data changes. If you want to query the database without observing changes, you can\nuse `Maybe\u003cT\u003e` or `Single\u003cT\u003e`. If a `Single\u003cT\u003e` query returns `null`,\nRoom will throw\n[EmptyResultSetException](/reference/android/arch/persistence/room/EmptyResultSetException).\n\n\nUPDATE or DELETE queries can return `void` or `int`. If it is an `int`,\nthe value is the number of rows affected by this query.\n\n\nYou can return arbitrary POJOs from your query methods as long as the fields of the POJO match\nthe column names in the query result.\nFor example, if you have class: \n\n```\n class UserName {\n public String name;\n @ColumnInfo(name = \"last_name\")\n public String lastName;\n }\n \n```\nYou can write a query like this: \n\n```\n @Query(\"SELECT last_name, name FROM user WHERE uid = :userId LIMIT 1\")\n public abstract UserName findOneUserName(int userId);\n \n```\nAnd Room will create the correct implementation to convert the query result into a `UserName` object. If there is a mismatch between the query result and the fields of the POJO, as long as there is at least 1 field match, Room prints a [CURSOR_MISMATCH](/reference/android/arch/persistence/room/RoomWarnings#CURSOR_MISMATCH) warning and sets as many fields as it can.\n\n\u003cbr /\u003e\n\nSummary\n-------\n\n| ### Public methods ||\n|-----------|-----------------------------------------------------------------------------------------------------|\n| ` String` | ` `[value](/reference/android/arch/persistence/room/Query#value())`() ` The SQLite query to be run. |\n\n| ### Inherited methods |\n|-----------------------|---|\n| From interface ` java.lang.annotation.Annotation ` |-----------------------------------------|-------------------------| | ` abstract Class\u003c? extends Annotation\u003e` | ` annotationType() ` | | ` abstract boolean` | ` equals(Object arg0) ` | | ` abstract int` | ` hashCode() ` | | ` abstract String` | ` toString() ` | ||\n\nPublic methods\n--------------\n\n### value\n\n```\nString value ()\n```\n\nThe SQLite query to be run.\n\n\u003cbr /\u003e\n\n| Returns ||\n|----------|-----------------------------|\n| `String` | The query to be run. \u003cbr /\u003e |\n\n-\n\n Annotations\n -----------\n\n - [ColumnInfo](/reference/android/arch/persistence/room/ColumnInfo)\n - [ColumnInfo.Collate](/reference/android/arch/persistence/room/ColumnInfo.Collate)\n - [ColumnInfo.SQLiteTypeAffinity](/reference/android/arch/persistence/room/ColumnInfo.SQLiteTypeAffinity)\n - [Dao](/reference/android/arch/persistence/room/Dao)\n - [Database](/reference/android/arch/persistence/room/Database)\n - [Delete](/reference/android/arch/persistence/room/Delete)\n - [Embedded](/reference/android/arch/persistence/room/Embedded)\n - [Entity](/reference/android/arch/persistence/room/Entity)\n - [ForeignKey](/reference/android/arch/persistence/room/ForeignKey)\n - [ForeignKey.Action](/reference/android/arch/persistence/room/ForeignKey.Action)\n - [Ignore](/reference/android/arch/persistence/room/Ignore)\n - [Index](/reference/android/arch/persistence/room)\n - [Insert](/reference/android/arch/persistence/room/Insert)\n - [OnConflictStrategy](/reference/android/arch/persistence/room/OnConflictStrategy)\n - [PrimaryKey](/reference/android/arch/persistence/room/PrimaryKey)\n - [Query](/reference/android/arch/persistence/room/Query)\n - [RawQuery](/reference/android/arch/persistence/room/RawQuery)\n - [Relation](/reference/android/arch/persistence/room/Relation)\n - [SkipQueryVerification](/reference/android/arch/persistence/room/SkipQueryVerification)\n - [Transaction](/reference/android/arch/persistence/room/Transaction)\n - [TypeConverter](/reference/android/arch/persistence/room/TypeConverter)\n - [TypeConverters](/reference/android/arch/persistence/room/TypeConverters)\n - [Update](/reference/android/arch/persistence/room/Update)\n-\n\n Classes\n -------\n\n - [DatabaseConfiguration](/reference/android/arch/persistence/room/DatabaseConfiguration)\n - [InvalidationTracker](/reference/android/arch/persistence/room/InvalidationTracker)\n - [InvalidationTracker.Observer](/reference/android/arch/persistence/room/InvalidationTracker.Observer)\n - [Room](/reference/android/arch/persistence/room/Room)\n - [RoomDatabase](/reference/android/arch/persistence/room/RoomDatabase)\n - [RoomDatabase.Builder](/reference/android/arch/persistence/room/RoomDatabase.Builder)\n - [RoomDatabase.Callback](/reference/android/arch/persistence/room/RoomDatabase.Callback)\n - [RoomDatabase.MigrationContainer](/reference/android/arch/persistence/room/RoomDatabase.MigrationContainer)\n - [RoomWarnings](/reference/android/arch/persistence/room/RoomWarnings)\n - [RxRoom](/reference/android/arch/persistence/room/RxRoom)\n-\n\n Enums\n -----\n\n - [RoomDatabase.JournalMode](/reference/android/arch/persistence/room/RoomDatabase.JournalMode)\n-\n\n Exceptions\n ----------\n\n - [EmptyResultSetException](/reference/android/arch/persistence/room/EmptyResultSetException)"]]