skip to content

In Room, how do you declare a composite primary key and a unique index on an entity, and what does each one generate?

level: middleimportance: should knowfreq 45%

answer

  1. the key lives on @Entity
  2. column names, not two @PrimaryKey
  3. Index(unique = true) in indices
  4. index_<table>_<columns> naming
  5. Room 3.0 WITHOUT ROWID option

basics

~20 s

A composite key goes in @Entity(primaryKeys = [...]) and becomes a PRIMARY KEY(a, b) table constraint; a unique index goes in @Entity(indices = [Index(value = [...], unique = true)]) and becomes a separate CREATE UNIQUE INDEX statement.

solid answer

~40 s

`@PrimaryKey` marks a single-column key; for several columns you list their column names in `@Entity(primaryKeys = ["recipe_id", "position"])`, and Room writes `` PRIMARY KEY(`recipe_id`, `position`) `` into the `CREATE TABLE`. Putting `@PrimaryKey` on two properties does not build a composite key; the processor rejects it. `primaryKeys` has no auto-generation, so the app supplies both values. A unique index is declared separately: `indices = [Index(value = ["name"], unique = true)]` generates `` CREATE UNIQUE INDEX IF NOT EXISTS `index_tags_name` ON `tags` (`name`) ``, and SQLite then rejects a duplicate name. `@ColumnInfo(index = true)` is the shortcut for a non-unique single-column index. Indices on parent classes or `@Embedded` types are not inherited unless re-declared, and Room 3.0 adds `withoutRowId` for tables with composite or non-integer keys.

go deeper

for a junior

Remember that a composite key is declared with @Entity(primaryKeys) and a unique column with Index(unique = true) in @Entity(indices).

for a middle

Explain the generated SQL: the PRIMARY KEY table constraint, separate CREATE UNIQUE INDEX statements, default index names, and why indices on parents are dropped.

for a senior

Judge which indices earn their write cost, predict the constraint failures a unique index adds to inserts, and know when Room 3.0's withoutRowId fits a table.

for a principal

Choose between natural composite keys and surrogate ids with unique indices as a team default, weighing sync, merges and later schema changes.

## When one column is not the key In the recipe app each ingredient line belongs to a recipe and has a position in its list: the pair (`recipe_id`, `position`) identifies a row, and neither column does alone. Tags need the opposite shape: a surrogate id as the key, plus a guarantee that no two tags share a name. Room expresses both on the `@Entity` annotation rather than on individual properties. ## Composite primary keys ```kotlin @Entity(tableName = "ingredients", primaryKeys = ["recipe_id", "position"]) data class Ingredient( @ColumnInfo(name = "recipe_id") val recipeId: Long, val position: Int, val text: String, ) ``` - **`primaryKeys` takes column names**, so after a `@ColumnInfo(name = ...)` rename you list `recipe_id`, not the property name `recipeId`. - Room writes the key as a table constraint at the end of the `CREATE TABLE`: `` PRIMARY KEY(`recipe_id`, `position`) ``. - **Two `@PrimaryKey` annotations are an error**, not a composite key. `@PrimaryKey` marks one property, or an `@Embedded` property whose columns then all form the key. - `primaryKeys` has **no auto-generation**: the app supplies both values, and inserting a duplicate pair violates the key unless the DAO picks another conflict strategy (the lesson on DAOs covers those). - **Column order matters** to SQLite: the key's index helps lookups by `recipe_id` alone but not by `position` alone. How SQLite uses indices belongs to the SQLite material. ## Indices and unique indices ```kotlin @Entity( tableName = "tags", indices = [Index(value = ["name"], unique = true)], ) data class Tag( @PrimaryKey(autoGenerate = true) val id: Long = 0, val name: String, ) ``` Room emits each index as **its own statement** after the table, not as a constraint inside it: ```sql CREATE UNIQUE INDEX IF NOT EXISTS `index_tags_name` ON `tags` (`name`) ``` | Declaration | Generates | Typical use | |---|---|---| | `@ColumnInfo(index = true)` | `CREATE INDEX` on one column | a column queries filter on | | `Index(value = ["a", "b"])` | a composite `CREATE INDEX` | filters on `a`, then `a` and `b` | | `Index(value = ["name"], unique = true)` | `CREATE UNIQUE INDEX` | a natural key such as a tag name | | `Index(..., orders = [...])` | per-column `ASC` or `DESC` | a multi-column index serving an `ORDER BY` | Points that come up in interviews: 1. **Default names** are `index_<table>_<columns joined by _>`. Set `name` when a query refers to the index; never rely on the generated name. 2. **Indices are not inherited.** An index declared on a parent class, or inside a type used with `@Embedded`, is dropped with a build warning unless you re-declare it on the entity, or set `inheritSuperIndices = true` for parent classes. 3. A **unique index is enforced by SQLite**: a second tag with the same name makes the write fail with a constraint error, whatever Kotlin code produced it. 4. Every index costs write time and space, so index the columns that queries actually filter, sort or join on. ## Room 3.0: tables without a rowid Room 3.0 added **`@Entity(withoutRowId = true)`** (in 3.0.0-alpha06), which creates the table with SQLite's `WITHOUT ROWID` option. Room's documentation describes it as useful for tables whose primary key is small, non-integer or composite, like the ingredient lines above, because skipping the separate row id can save space and time. Such a table cannot use `@PrimaryKey(autoGenerate = true)`, and turning the option on for an existing table changes its `CREATE TABLE`, so it needs a migration. Room 2.x has no equivalent property. ## Mistakes to avoid - Expecting two `@PrimaryKey` properties to form a composite key. - Listing property names in `primaryKeys` or `Index(value = ...)` where Room expects the renamed column names. - Assuming an index declared on a base class reaches every entity that extends it. - Using a unique index and then being surprised that a plain insert of a duplicate fails rather than updating the row. - Adding a unique index to a table that already holds duplicates: creating the index fails when the migration runs, so that migration has to clean the data first. - Declaring the key's columns again as a unique index; the primary key already enforces uniqueness and already has an index behind it.

  • What happens to an @Index declared on a class that a Room entity extends?
    Room drops it by default and prints a build warning, because SQLite index names must be unique across tables and an inherited index would be a surprise. Re-declare it on the entity, or set `inheritSuperIndices = true` on `@Entity`; Room then renames the inherited index with the default `index_<table>_<columns>` scheme.
  • In Room 3.0, when is @Entity(withoutRowId = true) worth turning on?
    For tables keyed by a small, non-integer or composite primary key and read through that key, such as ingredient lines keyed by recipe and position; skipping the separate row id can save space and time. It rules out an auto-generated key, and enabling it on an existing table changes the `CREATE TABLE`, so it ships with a migration.

  • Two @PrimaryKey annotations make a composite primary key.
  • A composite primary key can still auto-generate one of its columns.
  • Room enforces unique indices in generated DAO code rather than in SQLite.
  • Indices declared on a parent class always carry over to the entity.
  • primaryKeys lists Kotlin property names even after @ColumnInfo renames them.

Assumes Room 3.0; @Entity(withoutRowId) arrived in 3.0.0-alpha06, while primaryKeys, Index and unique indices work the same in Room 2.x.