skip to content

In Room, what does @ForeignKey with onDelete = CASCADE declare on a child entity, and why does Room warn about an unindexed child column?

level: middleimportance: should knowfreq 50%

answer

  1. a clause in the child's CREATE TABLE
  2. SQLite enforces it, not Room
  3. parent side needs a key or unique index
  4. child side wants an index
  5. default action is NO_ACTION

basics

~20 s

@ForeignKey adds a FOREIGN KEY clause to the child table's CREATE TABLE, so SQLite deletes a recipe's ingredients when the recipe is deleted. Room warns about a missing child index because every parent delete or key change would scan the whole child table.

solid answer

~40 s

A foreign key is declared on the child: `@Entity(foreignKeys = [ForeignKey(entity = Recipe::class, parentColumns = ["id"], childColumns = ["recipe_id"], onDelete = ForeignKey.CASCADE)])`. Room writes it into the child's `CREATE TABLE` and SQLite enforces it: an ingredient for a missing recipe is rejected, and deleting a recipe deletes its ingredients. Without `onDelete` the action is `NO_ACTION`, so that delete fails while children exist; `RESTRICT`, `SET_NULL` and `SET_DEFAULT` are the other choices. The referenced parent columns must be its primary key or a unique index, or the build fails. Room also prints `ROOM_MISSING_FOREIGN_KEY_CHILD_INDEX` when `recipe_id` has no index, because SQLite must find the children on every parent delete or key change, and without an index that means scanning the child table.

go deeper

for a junior

Know that @ForeignKey sits on the child entity, that CASCADE deletes children with their parent, and that the default action is NO_ACTION.

for a middle

Explain who enforces the constraint, the parent-side uniqueness Room checks at build time, and why the missing child index warning matters for writes.

for a senior

Spot the production traps: REPLACE inserts cascading deletes, bulk imports that need deferred constraints, and foreign-key edits that require a migration.

for a principal

Decide where integrity lives for synced data: strict foreign keys that reject out-of-order writes, or looser tables that the sync layer must keep consistent.

## Integrity that the database enforces In the recipe app every ingredient belongs to a recipe. A **foreign key** makes SQLite guarantee that: an ingredient cannot point at a recipe that does not exist, and the schema states what happens to ingredients when their recipe goes. In Room you declare it on the **child** entity, inside `@Entity(foreignKeys = [...])`. Room writes it into the child table's `CREATE TABLE`, and from then on **SQLite**, not Room's generated code, checks it on every write. ```kotlin @Entity( tableName = "ingredients", foreignKeys = [ ForeignKey( entity = Recipe::class, parentColumns = ["id"], childColumns = ["recipe_id"], onDelete = ForeignKey.CASCADE, ), ], indices = [Index("recipe_id")], ) data class Ingredient( @PrimaryKey(autoGenerate = true) val id: Long = 0, @ColumnInfo(name = "recipe_id") val recipeId: Long, val text: String, ) ``` The child table's DDL then ends with a clause of the form `` FOREIGN KEY(`recipe_id`) REFERENCES `recipes`(`id`) ... ON DELETE CASCADE ``. ## The parts of @ForeignKey | Property | Meaning | Default | |---|---|---| | `entity` | the parent entity class, part of the same database | required | | `parentColumns` | the referenced columns in the parent | required | | `childColumns` | the columns in this entity, as many as `parentColumns` | required | | `onDelete` | what happens to children when the parent row is deleted | `NO_ACTION` | | `onUpdate` | what happens to children when the parent key changes | `NO_ACTION` | | `deferred` | check at the end of the transaction instead of per statement | `false` | ## The five actions - **`NO_ACTION`**, the default: SQLite makes no effort to repair the reference, so deleting a recipe that still has ingredients fails the constraint. - **`RESTRICT`**: also refuses, but at the moment the parent changes, even when the constraint is deferred. - **`SET_NULL`**: the children's `recipe_id` becomes `NULL`, which only works if that column is nullable. - **`SET_DEFAULT`**: the children's column takes its `@ColumnInfo(defaultValue = ...)`. - **`CASCADE`**: deleting the recipe deletes its ingredients; on update, the children's key follows the parent's new key. ## Choosing an action per relationship The action encodes ownership, so pick it per foreign key rather than by habit: - **Owned children** such as a recipe's ingredient lines: `CASCADE`, because they mean nothing without the recipe. - **Optional links** such as a recipe's nullable `category_id`: `SET_NULL`, so deleting a category leaves the recipe uncategorised instead of deleting it. - **Records that must outlive edits**, such as a cooking log pointing at the recipe it used: `RESTRICT` or the default `NO_ACTION`, so the app must decide explicitly what happens before the parent can go. ## Two checks Room makes at build time 1. **The parent side must be unique.** SQLite requires the referenced columns to be the parent's primary key or covered by a unique index. Room verifies this during compilation and reports an error if it is missing. 2. **The child side should be indexed.** Without an index on `recipe_id`, every delete of a recipe, or change of its key, makes SQLite scan the whole `ingredients` table to find the children. SQLite does not create that index for you, so Room prints the **`ROOM_MISSING_FOREIGN_KEY_CHILD_INDEX`** warning (the `RoomWarnings.MISSING_INDEX_ON_FOREIGN_KEY_CHILD` constant). It is a warning, not an error; the fix is `Index("recipe_id")` in `indices` or `@ColumnInfo(index = true)` on the property. ## Pitfalls interviewers probe - **Replace means delete.** An `@Insert` with `OnConflictStrategy.REPLACE` that hits an existing recipe resolves the conflict by deleting the old row before inserting the new one, and that delete fires `ON DELETE CASCADE`: the recipe's ingredients disappear. `@Update` or `@Upsert` change the row in place and keep them. The DAO lesson covers the conflict strategies themselves. - **Bulk imports.** Writing children before their parents inside one transaction fails an immediate constraint at the first child; `deferred = true` moves the check to commit, when everything is consistent again. - **A foreign key is not a relation.** It enforces integrity on writes; reading a recipe together with its ingredients is a separate `@Relation` declaration, covered in the lesson on relations. Neither implies the other. - **The schema is the contract.** Adding, removing or changing a foreign key changes the child's `CREATE TABLE`, so it ships with a version bump and a migration.

  • Why can an @Insert with OnConflictStrategy.REPLACE on a Room parent row wipe out its children?
    `REPLACE` resolves a key conflict by deleting the existing row and inserting the new one. With `onDelete = ForeignKey.CASCADE` on the children, that delete cascades, so the recipe's ingredients are deleted even though the recipe comes straight back. Use `@Update` or `@Upsert`, which change the row in place, when children must survive.
  • When would you set deferred = true on a Room @ForeignKey?
    When one transaction writes rows in an order that is briefly inconsistent, such as importing ingredients before their recipes from a server payload. A deferred constraint is checked at commit, so the transaction succeeds if every reference is valid by then; an immediate constraint fails at the first orphaned child.

  • Room checks foreign keys in its generated DAO code before each write.
  • Declaring a foreign key lets you load a recipe together with its ingredients.
  • The default onDelete action of a Room @ForeignKey is CASCADE.
  • A foreign key can reference any parent column, even one without a unique index.
  • The child-index warning is harmless because SQLite indexes foreign keys itself.