Skip to the page

NoSQL and MongoDB · mid

Flexible attributes: JSONB, columns, EAV or documents

A catalog where each category has different attributes can use JSONB, a wide table, an attribute-value table, or a document database. A hybrid is often best.

The notes

What you must know

  • Options: a wide table with many NULL columns (simple and typed); an attribute-value (EAV) table (flexible but painful queries and no types); JSONB; a table per category; a document database.
  • json stores the text as given. jsonb stores a parsed binary form, is faster to query and can be indexed.
  • Query with the containment operator: WHERE attrs @> '{"ram_gb": 8}'. A GIN index on attrs supports it.
  • GIN operator classes: the default jsonb_ops supports @>, ?, ?|, ?&, @? and @@. jsonb_path_ops is smaller and faster but supports only @>, @? and @@.
  • For one hot key, use a B-tree expression index, for example on ((attrs->>'brand')).
  • Hybrid design: fields used for filters, sorting and joins (price, brand, category, stock) are real columns. The long tail goes in JSONB, with checks in the app or a CHECK constraint.
  • The planner keeps weak statistics inside JSONB values. A stored generated column for a hot key gets normal statistics and indexes.
  • MySQL has a JSON type, indexed through generated columns, functional indexes or multi-valued indexes.

The red pen

Common traps: mistake → fix

  • Mistake: Put everything in JSONB, including prices and foreign keys

    Fix: keep core fields as typed columns.

  • Mistake: json and jsonb are the same

    Fix: only jsonb can be indexed well.

  • Mistake: EAV is the safe flexible choice

    Fix: queries need many self-joins and nothing is typed.

Easy to hard

Questions interviewers ask, easy to hard

  1. How would you store product attributes that differ by category?
  2. What is the difference between json and jsonb?
  3. How do you index a JSONB column?
  4. Which fields stay as normal columns, and why?

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview