AI Hints
PostgreSQL · Lesson 40 of 120

JSONB Basics

JSON in a column.

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

Some data doesn't fit neat columns. Customer preferences, book details that vary. JSONB stores JSON documents in a column, in a fast binary form.

  • Varied data
  • JSON documents
  • jsonb

Book details

First, one book's whole details document. The arrow operator gets a value as JSON. The double arrow gets it as text. Run it. The full document, then pages and format for three books.

query.sqlsql
SELECT details FROM books WHERE book_id = 2;

SELECT title,
       details -> 'pages'   AS pages,
       details ->> 'format' AS format
FROM books
ORDER BY book_id
LIMIT 3;
Output
                           details
--------------------------------------------------------------
 {"pages": 353, "format": "hardcover", "language": "English"}
(1 row)

       title        | pages |  format
--------------------+-------+-----------
 The Silent Orchard | 550   | hardcover
 Code of the River  | 353   | hardcover
 Stars Over Lagos   | 466   | paperback
(3 rows)

json vs jsonb

Plain JSON keeps the exact text, including spaces and key order. JSONB parses it into a binary form. It's faster to query, can be indexed, and is what you should use almost always.

json

  • Exact textKeeps key orderSlower to query

jsonb

  • Binary formIndexableUse this one

Summary

JSONB stores documents in a column, and arrow operators read values out. Next, querying inside JSONB.

Key takeaways
  • jsonb
  • ->
  • ->>
Next up: Querying JSONB — filter by what is inside