Part 14 / Topic 8 of 10
JSONB or columns?
The real design question, as a checklist. Columns when: the fields are known, queried, constrained, joined — anything Part 9 would draw in the ER diagram. JSONB when:
- The shape genuinely varies per row (an event's payload differs by event type — shopdb's exact case).
- You're storing a third party's document and consuming it whole (webhook bodies, API responses).
- Attributes are sparse and user-defined (product specs: laptops have RAM, knives have blade length).
The failure mode to refuse: the "everything bag" — core business fields (price! status! customer_id!) buried in a jsonb column because migrations felt like work. Those fields can't be foreign-keyed, CHECK-constrained or sanely joined, and six months later every query is (payload->>'price')::numeric with a prayer. The litmus test: if a field is in every row and queries filter or join on it, it's a column. Hybrid tables — typed columns for the backbone, one jsonb for the honest leftovers — are the professional normal.
🧪 Quick quiz — answer from memory, then check.
- Three honest JSONB use cases?
- The litmus test for "this belongs in a column"?
Show the answers
- Per-row varying shapes (events), third-party documents stored whole, sparse user-defined attributes.
- If it is present in every row and used in filters or joins, it deserves a real column, with types and constraints.
Done here? The practice set for Part 14 — 6 exercises with solutions — is on the part page.