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.
0
0
Database migrations in Android Kotlin
Introduction
You add a new column to a table in your app's database.
You rename or remove a table or column in your database.
You change the data type of a column in your database.
You want to fix a mistake in your database structure after releasing your app.
You add new tables to support new features in your app.
Syntax
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.
Examples
This migration adds a new table called
orders in version 3.Android Kotlin
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)") } }
This migration removes a temporary table
temp_data in version 4.Android Kotlin
val MIGRATION_3_4 = object : Migration(3, 4) { override fun migrate(database: SupportSQLiteDatabase) { database.execSQL("DROP TABLE IF EXISTS temp_data") } }
Sample App
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.
Android Kotlin
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()
OutputSuccess
Important Notes
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.
Summary
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.