In Room, what CREATE TABLE statement does an @Entity generate, and how do nullability, @PrimaryKey(autoGenerate) and @ColumnInfo shape it?
answer
- types map to SQLite affinities
- non-null type adds NOT NULL
- autoGenerate: INTEGER PRIMARY KEY AUTOINCREMENT
- DEFAULT skipped by whole-object inserts
- exported JSON holds createSql
basics
~20 sRoom writes CREATE TABLE IF NOT EXISTS with one column per property: the Kotlin type picks the affinity, a non-null type adds NOT NULL, autoGenerate makes an INTEGER PRIMARY KEY AUTOINCREMENT, and @ColumnInfo sets the name, affinity, collation, index and DEFAULT.
solid answer
~40 sRoom derives the DDL from the declarations. `Int`, `Long` and `Boolean` map to `INTEGER`, `String` to `TEXT`, `Float` and `Double` to `REAL`, `ByteArray` to `BLOB`; a non-null Kotlin type adds `NOT NULL` and a nullable one does not. A plain `@PrimaryKey` becomes a `PRIMARY KEY(...)` table constraint, while `@PrimaryKey(autoGenerate = true)` makes the column `INTEGER PRIMARY KEY AUTOINCREMENT`, and `@Insert` treats an id of `0` (or `null` for a nullable type) as unset. `@ColumnInfo` renames the column, overrides `typeAffinity`, adds a `COLLATE`, a single-column index or a `DEFAULT`; that default applies only when a write omits the column, never to `@Insert` of a whole object. Room 3.0 adds `PrimaryKey.algorithm`: `AUTOINCREMENT` by default, or `ROWID`. The exported schema JSON shows each table's `createSql`.
code
kotlin · 7 lines@Entity(tableName = "recipes")
data class Recipe(
@PrimaryKey(autoGenerate = true) val id: Long = 0,
val title: String,
@ColumnInfo(defaultValue = "2") val servings: Int,
val notes: String?,
)go deeper
Know that Room writes CREATE TABLE for you, that Kotlin types pick column types, and that autoGenerate lets SQLite assign an id when you insert 0.
Walk through the mapping: affinities, NOT NULL from non-null types, the AUTOINCREMENT column autoGenerate produces, and why defaultValue never applies to a whole-object @Insert.
Read a schema change in a Kotlin diff: nullability, renamed properties and new defaults all change the DDL, and the exported createSql is where review catches them before release.
Set the team's id policy: auto-generated AUTOINCREMENT, Room 3.0's cheaper ROWID, or client-made ids for synced rows, weighing id reuse against sync needs.
## From declaration to DDL Room never asks you to write `CREATE TABLE`; it **derives** the statement from the entity at build time and runs it when the database file is first created. Knowing the mapping lets you predict the schema, read it back from the exported JSON, and notice when a harmless-looking Kotlin edit changes it. For the recipe entity in the example (an auto-generated id, a title, a servings count with a default, optional notes), Room writes a statement of this shape: ```sql CREATE TABLE IF NOT EXISTS `recipes` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `title` TEXT NOT NULL, `servings` INTEGER NOT NULL DEFAULT 2, `notes` TEXT) ``` ## Types and nullability | Kotlin property | Column affinity | Constraint | |---|---|---| | `Int`, `Long`, `Short`, `Byte`, `Boolean` | `INTEGER` | `NOT NULL` when the type is non-null | | `Float`, `Double` | `REAL` | `NOT NULL` when the type is non-null | | `String` | `TEXT` | `NOT NULL` when the type is non-null | | `ByteArray` | `BLOB` | `NOT NULL` when the type is non-null | - **Nullability is schema.** `val notes: String?` produces a nullable column; changing it to `String` adds `NOT NULL`, a schema change that existing installs must migrate. - **`@ColumnInfo(typeAffinity = ...)`** overrides the derived affinity with `TEXT`, `INTEGER`, `REAL` or `BLOB`; the default, `UNDEFINED`, means "derive it from the type". What an affinity means to SQLite itself is covered with SQLite. - Other types need a column type converter, the subject of its own lesson; enums and UUIDs have built-in ones. ## Primary keys 1. **`@PrimaryKey val id: Long`** with no auto-generation: the column is declared like any other and the key becomes a table constraint, `` PRIMARY KEY(`id`) ``. The app supplies every id. 2. **`@PrimaryKey(autoGenerate = true) val id: Long = 0`**: the column becomes `INTEGER PRIMARY KEY AUTOINCREMENT`, so the property should map to `INTEGER`. On `@Insert`, Room treats `0` (or `null` for a `Long?` or `Int?`) as "not set" and lets SQLite assign the id. 3. **Room 3.0's `algorithm`** (added in 3.0.0-rc01) picks how SQLite generates ids: `PrimaryKey.Algorithm.AUTOINCREMENT`, the default, never reuses an id over the life of the file; `PrimaryKey.Algorithm.ROWID` lets SQLite reuse the ids of deleted rows and is cheaper. Room 2.x has no such property; its auto-generated keys always use `AUTOINCREMENT`. ## @ColumnInfo and the DEFAULT trap - `name` renames the column; pin it when the Kotlin name might be refactored. - `index = true` adds a single-column index named `index_<table>_<column>`. - `collate` adds a collation such as `NOCASE`; left unspecified, SQLite compares as `BINARY`. - **`defaultValue`** adds a `DEFAULT` clause. `NULL` and `CURRENT_TIMESTAMP` are read as SQL; write `'NULL'` with single quotes to store the text. The trap: **`@Insert` of a whole entity always writes the object's own value**, so `DEFAULT 2` never applies to it. The default applies only to an `INSERT` written in `@Query` that omits the column, or to a partial insert through `@Insert(entity = Recipe::class)` whose parameter class has no property for that column. If the app needs a Kotlin-side default too, give the constructor parameter one. ## Where to see what Room generated - The **exported schema JSON**, when a schema folder is configured, records each entity's `createSql`, every field with its `affinity` and `notNull` flag, the primary key with `autoGenerate`, and the indices and foreign keys. - The generated `<Database>_Impl` source in the build directory contains the same statements. - At runtime Room checks the file's stored identity hash against the compiled schema whenever it opens the database, so a schema edit without a version bump fails at first open. ## Kotlin edits that change the table Each of these looks like a refactor in Kotlin and is a schema change in SQLite, so each needs a version bump and a migration on a shipped app: 1. Renaming a property that has no pinned `@ColumnInfo(name = ...)`: the column is renamed. 2. Turning `String?` into `String`, or the reverse: `NOT NULL` appears or disappears. 3. Adding or changing `defaultValue`, `collate`, `typeAffinity` or `index`. 4. Switching a key to `autoGenerate`, or, in Room 3.0, changing its `algorithm`. By contrast, adding an `@Ignore` property in the class body or renaming a property whose column name is pinned leaves the table alone. Reading `createSql` in a code review is the cheapest way to tell the two groups apart before release.
- Why declare a Room auto-generated id as `val id: Long = 0` rather than `Long?`?Both work: on insert Room treats `0` for `Long` or `Int`, and `null` for `Long?` or `Int?`, as not set and lets SQLite assign the id. A non-null `Long = 0` spares every caller a null check once a row is loaded; a nullable id states 'not saved yet' in the type. Either way, the app should not pick ids itself for an auto-generated key.
- When would you choose Room 3.0's PrimaryKey.Algorithm.ROWID over the default?When ids only need to be unique among live rows, such as a local cache table, `ROWID` skips the extra work `AUTOINCREMENT` does to guarantee an id is never reused, which Room's own documentation calls the slower choice. Keep `AUTOINCREMENT` when an id can outlive its row, for example when it is sent to a server, so a recycled id cannot point at the wrong recipe.
- Room stores String columns as VARCHAR with a fixed maximum length.
- Nullable and non-null Kotlin properties produce identical columns.
- @ColumnInfo(defaultValue) fills the column whenever @Insert saves an object.
- autoGenerate works on any primary key type, including String.
- Changing a property from String? to String does not change the schema.
Assumes Room 3.0; PrimaryKey.algorithm arrived in 3.0.0-rc01 with AUTOINCREMENT as the default, while Room 2.x auto-generated keys always use AUTOINCREMENT.