Performing database migrations with the SQLite API always made me feel like I was defusing a bomb — as if I was one wrong move away from making the app explode in my users’ hands. If you’re using Room to handle your database operations, migrations are as easy as flipping a switch.

With Room, if you change the database schema but don’t upgrade the version, your app will crash. If you upgrade the version but don’t provide any migrations your app will crash or, the database tables are dropped and your users will lose their data. Don’t risk your (app’s) life by guessing w̶h̶i̶c̶h̶ ̶s̶w̶i̶t̶c̶h̶ ̶t̶o̶ ̶f̶l̶i̶p̶ how to implement migrations. Rather, understand how Room works internally, to migrate your database with confidence.

Database migrations under the hood

What SQLite API does

SQLite databases handle schema changes with the help of database versioning. More precisely, every time you alter your schema by adding, removing or modifying tables, you have to increase the database version number and update your implementation of SQLiteOpenHelper.onUpgrade method. This is how you tell SQLite what it needs to do when going from an old version to a new version.

This is also the first call that gets triggered when your app starts working with the database. SQLite will first try to handle the version upgrades and only then it will open the database.

What Room does

Room provides an abstraction layer to ease SQLite migrations in the form of the Migration class. A Migration class defines the actions that should be performed when migrating from one specific version to another. Room uses its own implementation of SQLiteOpenHelper and, in the onUpgrade method, will trigger the migrations you defined.

Here’s what happens when you access the database for the first time:

The Room database is built SQLiteOpenHelper.onUpgrade method is called and Room triggers the migrations The database is opened

If you don’t provide migrations but you increase the database version, your app might crash or your data may be lost, depending on some circumstances that we will consider below.