Choose Between Embedded Schemas and Associations

Learn when to prefer embedded schemas over associations, and when not to.

Advantages of embedded schemas

Embedded schemas have some advantages over associations.

  • Since the child records are stored with the parent, we don’t have to use joins or Repo.preload to fetch them. This can help with performance because we can avoid extra round-trips to the database. It also means the data is stored together on disk and in memory, which reduces expensive disk seek time and increases caching efficiency.

  • With schemas, we also have to create an accompanying migration every time we make changes. Embeds use unstructured JSON, so we only need to change our schema definition and leave the database alone. This is more flexible and can lead to more efficient iteration.

Disadvantages of embedded schemas

Embeds do not replace associations, though, and they can’t do the following things.

  • Since they are stored in a single column, we can’t do partial updates on a field-by-field basis on the embedded schema. Ecto supports field-level changes within changesets, but internally, the whole schema needs to be sent to the database even if we are only updating a single field.
  • Embeds don’t use foreign keys, which means we lose the referential integrity that databases provide with foreign keys.

The advantages and disadvantages over associations are shown below.

Get hands-on with 1200+ tech skills courses.