Sobes.tech
Junior — Middle

What is the difference between Query and RawQuery when using the Room library?

sobes.tech AI

Answer from AI

In the Room library for Android, the @Query annotation is used to write SQL queries that are compiled and checked at compile time. This helps prevent errors in queries and ensures type safety.

RawQuery is used for executing dynamic or complex SQL queries that cannot be expressed through @Query. It accepts a SupportSQLiteQuery object, allowing queries to be formed at runtime. However, such queries are not checked at compile time, which increases the risk of errors.

Example of using RawQuery:

@Dao
interface UserDao {
    @RawQuery
    fun getUsersViaRawQuery(query: SupportSQLiteQuery): List<User>
}

// Creating a query at runtime
val query = SimpleSQLiteQuery("SELECT * FROM users WHERE age > ?", arrayOf(18))
val users = userDao.getUsersViaRawQuery(query)

Summary:

  • @Query — static, compile-time checked queries.
  • @RawQuery — dynamic queries formed at runtime without compiler verification.