Room queries let your app save, change, remove, and get data from a database easily. This helps your app remember things even after closing.
Room queries (Insert, Update, Delete, Select) in Android Kotlin
/* Insert */ @Insert fun insertItem(item: Item) /* Update */ @Update fun updateItem(item: Item) /* Delete */ @Delete fun deleteItem(item: Item) /* Select */ @Query("SELECT * FROM item_table") fun getAllItems(): List<Item>
@Insert fun addUser(user: User)
@Update fun updateUser(user: User)
@Delete fun deleteUser(user: User)
@Query("SELECT * FROM user_table WHERE age > 18")
fun getAdultUsers(): List<User>This example shows how to insert, update, delete, and select users in a Room database using Kotlin. The User data class defines the table. UserDao interface has methods with Room annotations to perform database actions.
import androidx.room.* @Entity(tableName = "user_table") data class User( @PrimaryKey val id: Int, val name: String, val age: Int ) @Dao interface UserDao { @Insert fun insertUser(user: User) @Update fun updateUser(user: User) @Delete fun deleteUser(user: User) @Query("SELECT * FROM user_table") fun getAllUsers(): List<User> } // Usage example (not full app): fun main() { val userDao: UserDao = TODO("Get UserDao from Room database") val user = User(1, "Alice", 25) userDao.insertUser(user) // Save user val users = userDao.getAllUsers() // Get all users println(users) val updatedUser = user.copy(age = 26) userDao.updateUser(updatedUser) // Update age userDao.deleteUser(updatedUser) // Remove user }
Room database operations should be run on a background thread to keep the app smooth.
Always use suspend functions or RxJava for queries in real apps to avoid blocking the main thread.
Primary key is important to identify which row to update or delete.
Use @Insert, @Update, @Delete annotations for basic data changes.
Use @Query with SQL to read data from the database.
Room helps keep your data safe and easy to manage inside your app.
Practice
Solution
Step 1: Understand Room annotations for data changes
@Insert is used to add new data, @Update modifies existing data, and @Delete removes data.Step 2: Identify the annotation for adding records
Since adding means inserting new data, @Insert is the correct annotation.Final Answer:
@Insert -> Option BQuick Check:
Add new record = @Insert [OK]
- Confusing @Update with adding new data
- Using @Delete instead of @Insert
- Thinking @Query inserts data
Solution
Step 1: Recall SQL DELETE syntax
The correct SQL command to delete rows is DELETE FROM table WHERE condition.Step 2: Match correct syntax in options
@Query("DELETE FROM users WHERE id = :userId") matches the correct SQL syntax with parameter binding (:userId).Final Answer:
@Query("DELETE FROM users WHERE id = :userId") -> Option CQuick Check:
DELETE FROM table WHERE condition = correct syntax [OK]
- Using REMOVE instead of DELETE
- Omitting FROM keyword
- Adding * after DELETE
getAllUsers()?
@Query("SELECT * FROM users")
fun getAllUsers(): List<User>Solution
Step 1: Analyze the method signature
The method returns List<User>, which means a list of User objects.Step 2: Understand the SQL query
SELECT * FROM users returns all rows, so the method returns multiple User objects in a list.Final Answer:
A list of User objects -> Option DQuick Check:
Return type List<User> means multiple users [OK]
- Thinking it returns a single User
- Confusing return type with count
- Expecting a Boolean result
@Update
fun updateUser(user: User): Int {
return 1
}Solution
Step 1: Understand Room DAO method requirements
DAO methods with @Update must be abstract or interface methods without a body.Step 2: Identify the error in the method
This method has a body with a return statement, which is not allowed for Room DAO annotated methods.Final Answer:
The method should not have a body; it must be abstract -> Option AQuick Check:
Room DAO methods are abstract, no method body [OK]
- Adding method body in DAO interface
- Returning wrong types intentionally
- Missing @Update annotation
Solution
Step 1: Understand update options in Room
@Update requires a full entity object, so partial updates need @Query with SQL.Step 2: Check which method updates email by ID
@Query("UPDATE users SET email = :email WHERE id = :userId") fun updateEmail(userId: Int, email: String) uses @Query with SQL UPDATE statement and parameters for userId and email, which is correct.Final Answer:
@Query("UPDATE users SET email = :email WHERE id = :userId") fun updateEmail(userId: Int, email: String) -> Option AQuick Check:
Partial update needs @Query with SQL UPDATE [OK]
- Using @Update without full entity
- Using @Insert to update data
- Using @Delete for updates
Ready to prove it?
Pass the test and this pattern moves unknown
