Database migrations help you change your app's database safely when you update your app. They keep your data safe and your app working well.
Database migrations in Android Kotlin
val MIGRATION_1_2 = object : Migration(1, 2) { override fun migrate(database: SupportSQLiteDatabase) { database.execSQL("ALTER TABLE user ADD COLUMN age INTEGER NOT NULL DEFAULT 0") } }
This example shows a migration from version 1 to 2.
The migrate function runs SQL commands to update the database.
orders in version 3.val MIGRATION_2_3 = object : Migration(2, 3) { override fun migrate(database: SupportSQLiteDatabase) { database.execSQL("CREATE TABLE orders (id INTEGER PRIMARY KEY NOT NULL, userId INTEGER, amount REAL)") } }
temp_data in version 4.val MIGRATION_3_4 = object : Migration(3, 4) { override fun migrate(database: SupportSQLiteDatabase) { database.execSQL("DROP TABLE IF EXISTS temp_data") } }
This example shows a Room database with a migration from version 1 to 2. It adds a new column age to the user table. The migration is added when building the database.
import androidx.room.Room import androidx.room.RoomDatabase import androidx.room.Database import androidx.room.migration.Migration import androidx.sqlite.db.SupportSQLiteDatabase @Database(entities = [User::class], version = 2) abstract class AppDatabase : RoomDatabase() { abstract fun userDao(): UserDao } val MIGRATION_1_2 = object : Migration(1, 2) { override fun migrate(database: SupportSQLiteDatabase) { database.execSQL("ALTER TABLE user ADD COLUMN age INTEGER NOT NULL DEFAULT 0") } } // Usage example val db = Room.databaseBuilder(context, AppDatabase::class.java, "app-db") .addMigrations(MIGRATION_1_2) .build()
Always test migrations on real data to avoid data loss.
Each migration handles one step between two versions.
If you skip versions, you must provide migrations for each step or use fallback strategies.
Database migrations update your app's database without losing data.
They run SQL commands to change tables or columns safely.
Use migrations whenever you change your database schema.
Practice
What is the main purpose of a database migration in Android apps?
Solution
Step 1: Understand database migration purpose
Database migrations are used to change the structure of the database safely.Step 2: Identify data preservation goal
Migrations update tables or columns without deleting existing user data.Final Answer:
To update the database schema without losing existing data -> Option AQuick Check:
Migration = Safe schema update [OK]
- Thinking migrations delete all data
- Confusing migrations with backups
- Believing migrations only optimize queries
Which of the following is the correct way to define a migration from version 1 to 2 in Room database?
val MIGRATION_1_2 = object : Migration(1, 2) {
override fun migrate(database: SupportSQLiteDatabase) {
// ?
}
}Solution
Step 1: Understand Migration class usage
Migration requires SQL commands inside migrate() to change schema.Step 2: Identify correct SQL command
ALTER TABLE adds a new column safely; execSQL runs raw SQL.Final Answer:
database.execSQL("ALTER TABLE users ADD COLUMN age INTEGER DEFAULT 0") -> Option AQuick Check:
Migration uses execSQL with ALTER TABLE [OK]
- Using update() instead of execSQL
- Trying to insert or delete rows in migration
- Not providing default value for new column
Given this migration code, what will be the result after migrating from version 1 to 2?
val MIGRATION_1_2 = object : Migration(1, 2) {
override fun migrate(database: SupportSQLiteDatabase) {
database.execSQL("CREATE TABLE IF NOT EXISTS books (id INTEGER PRIMARY KEY, title TEXT)")
}
}Assuming version 1 had no books table.
Solution
Step 1: Analyze migration SQL command
CREATE TABLE IF NOT EXISTS creates the table only if it doesn't exist.Step 2: Check initial database state
Version 1 has no 'books' table, so it will be created.Final Answer:
A new table 'books' is created with columns 'id' and 'title' -> Option CQuick Check:
CREATE TABLE IF NOT EXISTS creates missing table [OK]
- Assuming migration fails if table exists
- Thinking CREATE TABLE is ignored
- Believing existing tables get deleted
What is wrong with this migration code from version 2 to 3?
val MIGRATION_2_3 = object : Migration(2, 3) {
override fun migrate(database: SupportSQLiteDatabase) {
database.execSQL("ALTER TABLE users ADD COLUMN email TEXT")
database.execSQL("ALTER TABLE users ADD COLUMN email TEXT")
}
}Solution
Step 1: Review SQL commands in migration
The code tries to add the 'email' column twice to the same table.Step 2: Understand SQLite behavior
Adding the same column twice causes a runtime error during migration.Final Answer:
The same column 'email' is added twice causing an error -> Option BQuick Check:
Duplicate column addition causes migration failure [OK]
- Ignoring duplicate column errors
- Thinking migration version is updated automatically
- Believing ALTER TABLE syntax is wrong here
You want to rename a column username to user_name in your Room database from version 3 to 4. SQLite does not support renaming columns directly. Which migration strategy is correct?
Solution
Step 1: Understand SQLite column rename limitation
SQLite does not support direct column renaming with ALTER TABLE.Step 2: Apply recommended migration pattern
Create a new table with desired schema, copy data, drop old table, rename new table.Final Answer:
Create a new table with the new column name, copy data, drop old table, rename new table -> Option DQuick Check:
Rename column = new table + copy data [OK]
- Trying to rename column with ALTER TABLE
- Deleting old table without copying data
- Adding new column but not removing old one
Ready to prove it?
Pass the test and this pattern moves unknown
