SQL · Module 13 · Lesson 51 min read

JSON & JSONB

JSON vs JSONB

JSONJSONB ✅
Storageexact textbinary, parsed
Keeps key order/whitespace/duplicates✅❌
Faster to query❌✅
Indexable (GIN)❌✅
Use JSONB almost always.

Reading values

OperatorReturnsExample
->JSONdata->'notifications'
->>textdata->>'theme'
#> / #>>by pathdata#>>'{notifications,bills}'
[] subscript (PG14+)JSONdata['theme']

Cast text results: (data->>'limit')::numeric

Searching

  • @> contains: data @> '{"theme": "dark"}' (GIN-indexable ⭐)
  • ? key exists: data ? 'language'
  • ?| any of the keys, ?& all of the keys
  • jsonb_path_query / @? – JSONPath queries

Modifying

  • Merge/overwrite keys: data || '{"theme": "light"}'
  • Set a nested value: jsonb_set(data, '{notifications,email}', 'true')
  • Remove a key: data - 'language'; remove a path: data #- '{a,b}'

Expanding and building

  • jsonb_each(data) / jsonb_each_text → key/value rows
  • jsonb_array_elements(arr) → one row per element
  • jsonb_object_keys(data)
  • Building: jsonb_build_object, jsonb_build_array, to_jsonb(row), jsonb_agg

Indexing

  • CREATE INDEX ON t USING gin (data); → speeds up @>, ?
  • Expression index for one key: CREATE INDEX ON t ((data->>'theme'));

When to use JSONB (and when not)

✅ Settings, preferences, flexible metadata, raw API payloads, rarely queried attributes ❌ Anything you join on, filter on constantly, need constraints/foreign keys on, or update field by field all the time → make it a real column

You can still validate JSON with CHECK constraints: CHECK (data ? 'theme'), CHECK (jsonb_typeof(data->'limit') = 'number')

Example

SQL
CREATE TABLE user_settings (
  user_id INT PRIMARY KEY REFERENCES users(id),
  data    JSONB NOT NULL DEFAULT '{}'
          CHECK (jsonb_typeof(data) = 'object')
);
INSERT INTO user_settings VALUES
  (1, '{"theme": "dark",  "currency": "NPR", "notifications": {"bills": true, "email": false}, "pinned": ["Food", "Bills"]}'),
  (2, '{"theme": "light", "language": "ne",  "notifications": {"bills": false}}'),
  (3, '{"theme": "dark",  "currency": "USD", "limits": {"daily": 2000}}');

-- Reading
SELECT user_id,
       data->>'theme'                          AS theme,
       data->'notifications'->>'bills'         AS bill_alerts,
       data#>>'{limits,daily}'                 AS daily_limit,
       data['pinned'][0]                       AS first_pinned
FROM user_settings ORDER BY user_id;

-- Searching
SELECT user_id FROM user_settings WHERE data @> '{"theme": "dark"}';         -- 1, 3
SELECT user_id FROM user_settings WHERE data ? 'language';                  -- 2
SELECT user_id FROM user_settings WHERE (data#>>'{limits,daily}')::numeric > 1000;  -- 3

-- Modifying
UPDATE user_settings SET data = data || '{"theme": "light"}' WHERE user_id = 1;
UPDATE user_settings SET data = jsonb_set(data, '{notifications,email}', 'true') WHERE user_id = 1;
UPDATE user_settings SET data = data - 'language' WHERE user_id = 2;
SELECT data FROM user_settings WHERE user_id = 1;

-- Expanding JSON into rows
SELECT user_id, key, value FROM user_settings, jsonb_each_text(data) WHERE user_id = 3;
SELECT jsonb_array_elements_text(data->'pinned') AS pinned FROM user_settings WHERE user_id = 1;

-- Building JSON from tables
SELECT jsonb_build_object('user', u.name, 'city', u.city,
                          'top_tags', (SELECT jsonb_agg(DISTINCT t) FROM expenses e, unnest(e.tags) t WHERE e.user_id = u.id))
FROM users u WHERE u.id = 4;

-- Index for containment queries
CREATE INDEX idx_settings_data ON user_settings USING gin (data);