Interview frequency: …
Short answer
By increasing the version number and writing a Migration object that runs the appropriate ALTER TABLE statements, or relying on AutoMigration if the change is simple.
Explanation
If you modify an entity without writing a migration and raise the version, the app will crash with an IllegalStateException. Room lets you write a manual migration by executing precise SQL queries, and provides AutoMigration automatically starting with Room 2.4 for common operations such as adding new columns or tables with full compile-time verification through the schema export files.
Code example
val MIGRATION_1_2 = object : Migration(1, 2) {
override fun migrate(database: SupportSQLiteDatabase) {
database.execSQL("ALTER TABLE notes ADD COLUMN is_pinned INTEGER NOT NULL DEFAULT 0")
}
}
Room.databaseBuilder(context, AppDatabase::class.java, "notes.db")
.addMigrations(MIGRATION_1_2)
.build()Common mistakes
- Using fallbackToDestructiveMigration() in production code, which wipes the user's entire database on every change.
- Forgetting to add exportSchema = true in the database class for testing and monitoring migrations.