Entity–Attribute–Value (EAV) Model
Source: Dev.to
The Entity–Attribute–Value (EAV) model is a database design pattern that lets you define entity attributes at runtime. It’s especially useful when:
- Different records of the same entity have widely varying attributes.
- Many attributes apply only to a small subset of records, leading to sparse data.
- Adding new columns or storing lots of
NULLvalues would be impractical.
Instead of creating a fixed column for every possible attribute, EAV stores attributes in separate rows and assigns values only when they apply to a specific entity instance.
Example: Content Management System (CMS)
A CMS often needs to handle pages, articles, or media items that can have very different sets of metadata. With an EAV approach you might have three tables:
| Table | Purpose |
|---|---|
| Entity | Stores each CMS item (e.g., a page or article) with a primary key. |
| Attribute | Defines possible attributes (e.g., title, author, publish_date, seo_keywords). |
| Value | Holds the actual value for a given entity‑attribute pair, typically with columns like entity_id, attribute_id, and value. |
When a new custom field is needed (e.g., “reading_time”), you simply add a row to the Attribute table—no schema change is required.
When to Use EAV
- Frequently changing attributes – New attributes are added often.
- Sparse data – Most entities use only a small subset of the available attributes.
- Custom attributes – Administrators or users must define attributes at runtime without altering the database schema.
When Not to Use EAV
- Stable, well‑defined attributes – If the set of attributes is fixed and changes rarely, a traditional relational schema is more efficient.
- High‑performance requirements – EAV queries often involve multiple joins, which can degrade performance.
- Complex reporting and analytics – Aggregating and analyzing data across many EAV rows is more difficult and slower than with a conventional table layout.
Practical Advice
- Hybrid approach – Combine traditional tables for stable attributes with EAV tables for flexible, custom fields.
- Index wisely – Index the
entity_idandattribute_idcolumns in the Value table to improve join performance. - Limit scope – Use EAV only for entities that truly benefit from its flexibility; avoid applying it universally across the entire database.