Memra

JSON & JSONB

◈ 2 cards

Store and query semi-structured data — a job-critical Postgres skill.

Semi-structured data

jsonb stores JSON in an efficient binary form you can index and query. Each book has an attributes jsonb like {"format":"hardcover","pages":320}. Reach inside it:

  • attributes->'pages' — get the value as jsonb
  • attributes->>'format' — get it as text (note the double >)
  • (attributes->>'pages')::int — text, then cast to a number
  • attributes @> '{"format":"ebook"}' — containment (GIN-indexable, fast)
SELECT title FROM books WHERE attributes @> '{"format":"ebook"}';
expressionresulttypeattributes->'pages'320jsonbattributes->>'pages'320text(attributes->>'pages')::int+ 1321integerattributes->>'format'hardcovertextattributes @>'{"format":"ebook"}'falseboolean-> stays in jsonb, ->> gives text. Cast before comparing.
Every row here reads the same stored value, {"format":"hardcover","pages":320} on The Glass Forest. The single arrow keeps you inside jsonb (so 320 is still a JSON number); the double arrow exits to text, which is why comparing pages to a number needs the cast.
NORMAL ~/memra/learn/postgresql/json utf-8 LF