AI Hints
Home›PostgreSQL Tutorial›Updating and Building JSON
PostgreSQL · Lesson 45 of 120

JSONB or Columns?

Choose wisely.

⏱ 2 min read▶ Video at 39:11🎓 Free
Watch this lesson in the PostgreSQL courseWatch on YouTube ↗Full PostgreSQL course

JSONB is flexible, so it's tempting to put everything in it. But columns give you types, constraints and simpler queries. The trick is knowing which to use.

  • Flexible
  • But no rules
  • Choose wisely

Columns vs JSONB

Use columns for data every row has, that you filter, join or sum. Use JSONB for optional, varying data, like settings or extra details from another system.

Columns

  • Every row has itFilter, join, sumTypes + constraints

JSONB

  • Optional extrasVaries by rowRaw API data

A JSON rule with CHECK

You can still add rules to JSONB. This check makes sure pages, if present, is a number. Then we try to break it. Run it. The bad row is rejected.

query.sqlsql
ALTER TABLE books ADD CONSTRAINT pages_is_number
  CHECK (NOT details ? 'pages' OR jsonb_typeof(details -> 'pages') = 'number');

UPDATE books SET details = details || '{"pages": "lots"}'
WHERE book_id = 1;
Output
ALTER TABLE
ERROR:  new row for relation "books" violates check constraint "pages_is_number"
DETAIL:  Failing row contains (1, The Silent Orchard, Mira Hale, Mystery, 14.99, 58,
2016, {series,twist}, {"pages": "lots", "awards": ["Debut Prize"], "format":
"hardcove..., A detective returns to her home village, where an orchard hides ...).

Summary

Use columns for core data, JSONB for flexible extras, and checks to keep JSON honest. Next, enums and domains.

Key takeaways
  • Core: columns
  • Extras: jsonb
  • CHECK rules
Next up: Enums and Domains — custom types