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_id | colour | weight | weight_type |
|---|---|---|---|
| 1 | red | 12 | text |
| 2 | blue | 9 | text |
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