← Back to SQL, page 11

sql-0210 · Hard senior

What is the entity-attribute-value (EAV) pattern, and what problems does it cause?

EAV stores attributes as rows: entity_id, attribute name, value. It allows any attribute without schema changes, but loses types, NOT NULL and CHECK constraints, and foreign keys on values, and simple questions need one join or pivot per attribute. A JSON column, or real columns for common attributes plus JSON for the rare ones, is usually a better trade-off.

Full answer
sql
CREATE TABLE attrs (entity_id INTEGER, name TEXT, value TEXT);
INSERT INTO attrs VALUES (1, 'colour', 'red'), (1, 'weight', '12'), (2, 'colour', 'blue'), (2, 'weight', '9');
SELECT entity_id,
       MAX(CASE WHEN name = 'colour' THEN value END) AS colour,
       MAX(CASE WHEN name = 'weight' THEN value END) AS weight,
       typeof(MAX(CASE WHEN name = 'weight' THEN value END)) AS weight_type
FROM attrs GROUP BY entity_id ORDER BY entity_id;
entity_idcolourweightweight_type
1red12text
2blue9text

Reading two attributes already needs a pivot, every value is text, and nothing stops 'weight' being spelled 'wieght' or stored as 'heavy'.

Problems in larger systems:

  • No types: numbers compare as text unless cast on every query.
  • No constraints: required attributes cannot be enforced.
  • Query cost: each attribute in a filter is another self join or aggregation.

EAV can fit truly sparse, user-defined attributes, such as custom fields in a SaaS form builder, when the system mostly stores and displays them. For product catalogues with mostly known attributes, typed columns for the common ones plus a JSON column for the rest keep integrity where it matters.

sql
CREATE TABLE attrs (entity_id INTEGER, name TEXT, value TEXT);
INSERT INTO attrs VALUES (1, 'colour', 'red'), (1, 'weight', '12'), (2, 'colour', 'blue'), (2, 'weight', '9');
SELECT entity_id,
       MAX(CASE WHEN name = 'colour' THEN value END) AS colour,
       MAX(CASE WHEN name = 'weight' THEN value END) AS weight,
       typeof(MAX(CASE WHEN name = 'weight' THEN value END)) AS weight_type
FROM attrs GROUP BY entity_id ORDER BY entity_id;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • EAV stores attributes as rows
  • It loses types and constraints
  • Each attribute in a query adds a join or pivot
  • JSON plus typed common columns is often better

Common mistakes

  • Choosing EAV to avoid migrations and paying for it in every query
  • Comparing numeric EAV values as text

Follow-ups

  • How would you index a JSON attribute?
  • When is EAV acceptable?

Tips

  • Show the pivot needed to read two attributes