Lab 17: PostgreSQL JSONB Advanced

Time: 40 minutes | Level: Practitioner | DB: PostgreSQL 15

PostgreSQL's JSONB stores JSON in a binary, indexed form. It enables rich document queries inside a relational database — with the full power of SQL, transactions, and joins.


Step 1 — JSON vs JSONB

-- JSON: stores exact text (preserves whitespace, duplicate keys)
-- JSONB: binary format, deduplicates keys, supports indexing

CREATE TABLE comparison (
  id       SERIAL PRIMARY KEY,
  raw_json JSON,
  bin_json JSONB
);

INSERT INTO comparison (raw_json, bin_json) VALUES (
  '{"name": "Alice", "age": 28, "name": "Alice Updated"}',  -- duplicate key
  '{"name": "Alice", "age": 28, "name": "Alice Updated"}'
);

-- JSON preserves duplicate keys and whitespace
SELECT raw_json FROM comparison;
-- {"name": "Alice", "age": 28, "name": "Alice Updated"}

-- JSONB deduplicates (last value wins) and normalizes
SELECT bin_json FROM comparison;
-- {"age": 28, "name": "Alice Updated"}

💡 Use JSONB for almost everything — it supports indexing and is faster to query. Use JSON only when you need to preserve exact text representation (e.g., audit logs).


Step 2 — Setup: User Profiles with JSONB


Step 3 — Navigation Operators: -> and ->>

📸 Verified Output:


Step 4 — Containment and Existence Operators

📸 Verified Output (@> Python):


Step 5 — Modifying JSONB: jsonb_set, jsonb_insert


Step 6 — GIN Index and Query Performance

📸 Verified Output (with GIN):


Step 7 — jsonb_path_query and JSONB Aggregation


Step 8 — Capstone: Product Catalog with JSONB Specs


Summary

Operator
Input
Output
Use

->

key/index

JSONB

Navigate, preserves type

->>

key/index

TEXT

Extract as text

#>

path array

JSONB

Deep navigation

#>>

path array

TEXT

Deep extract as text

@>

JSONB

boolean

Containment (GIN indexable)

<@

JSONB

boolean

Is contained by

?

key

boolean

Key exists

`?

`

key array

boolean

?&

key array

boolean

All keys exist

||

JSONB

JSONB

Merge/concatenate

-

key

JSONB

Remove key

#-

path

JSONB

Remove by path

Last updated