← Back to SQL, page 19

sql-0366 · Medium mid

A team stores most product attributes in a single JSON column. When is that a good idea, and when does it hurt?

JSON columns suit sparse, varying attributes that are read as a whole, such as category-specific specifications. They hurt for fields that are filtered, joined, aggregated or constrained, because types, foreign keys and NOT NULL cannot be enforced inside the document and indexing is more limited. Keep core fields as columns and the long tail in JSON.

Full answer

Good fits:

  • Attributes that differ by product type (a laptop's RAM, a shirt's fabric).
  • Payloads from external systems stored for reference.
  • Settings read and written as a unit.

Problems when overused:

  • No column types: '12' and 12 both slip in; validation moves to the application.
  • No foreign keys or NOT NULL inside the document.
  • Queries become verbose (attrs->>'brand') and planners have poorer statistics on JSON paths.
  • Updating one key rewrites the whole value.

PostgreSQL jsonb with a GIN index supports containment queries (attrs @> '{"brand":"Acme"}'), and expression indexes serve specific paths. SQLite stores JSON as text and offers json_extract with expression indexes. A rule of thumb: once a key appears in WHERE, ORDER BY or a report, promote it to a real column.

Key points

  • JSON suits sparse, varying attributes
  • Core, filtered fields belong in columns
  • Constraints do not reach inside JSON
  • GIN and expression indexes help selected queries
  • Promote frequently queried keys

Common mistakes

  • Putting price and stock inside JSON
  • Using JSON to avoid schema design

Follow-ups

  • How would you validate JSON structure in the database?
  • How does EAV compare with JSON columns?

Tips

  • Give the promote-to-column rule