androidinterview.com

Android System Design Interview Questions

What is the difference between database normalization and denormalization?

Tier: CommonDifficulty: Easy

Normalization splits data into separate related tables to eliminate duplication, denormalization deliberately duplicates data across tables to avoid joins and make reads faster.

Take a users table that stores each user's city. Normalized, the city lives in its own table and the user row just holds a cityId. Denormalized, the city name is copied directly onto every user row.

  • Normalization minimizes storage and keeps data consistent, renaming a city means updating one row, not thousands. The cost is query performance, reading a user's city means joining two tables, and that join cost compounds as you join more of them.
  • Denormalization trades that join away. Reading a user's city is just reading the row, no join needed. The cost lands on writes, renaming a city now means updating every duplicated row, and if you miss one, the data disagrees with itself.

Formally the steps have names, the normal forms. First normal form means every column holds a single value rather than a list. Second means no column depends on only part of a composite key. Third normal form is the one worth being able to state on the spot, every non-key column depends on the key, the whole key, and nothing but the key. When people say a schema is normalized, third normal form is almost always what they mean.

Which one you want depends on what the system optimizes for. Normalize where data integrity matters most and writes need to stay clean and consistent, a banking system is the classic example. Denormalize where read speed matters most and the data doesn't change often, a real-time analytics dashboard or a feed that gets read far more than it's written. And when you denormalize, make one writer responsible for keeping the copies in step, because a duplicated field that nobody owns will drift, and then you have two versions of the truth and no way to say which is right.

On Android this shows up at a smaller scale in your local Room schema. A cache table often denormalizes on purpose, storing a post with the author's name and avatar URL inlined right on the row, because the whole point of the cache is to render a list fast with no query-time join. Eventual staleness across a few duplicated fields is an acceptable trade for a local cache in a way it usually isn't for a system of record, and the sync that refreshes the cache is the one writer keeping those copies honest.