Difficulty: Intermediate
What is JSONB in PostgreSQL, how is it different from JSON, and when should you use it?
JSONB is PostgreSQL's binary JSON type: the document is parsed once on write and stored in a decomposed binary form, so reads do not re-parse text and the column can be indexed with GIN or expression indexes. It lets you keep flexible, semi-structured attributes inside a normal ACID relational table. Use it for data whose shape varies, and keep core, frequently filtered fields as regular columns.
| Aspect | json | jsonb |
|---|---|---|
| Storage | Exact input text | Parsed binary representation |
| Write cost | Faster (just validates) | Slightly slower (converts) |
| Read and operators | Re-parses on every access | Fast, no re-parse |
| Key order and whitespace | Preserved | Not preserved |
| Duplicate keys | Kept | Last value wins |
| Indexing | Expression indexes only | GIN plus expression indexes |
Containment @> | Not supported | Supported |
Pick json only if you must preserve the exact original text, such as storing a webhook payload for audit. Otherwise use jsonb.
-> returns a JSON value, ->> returns text: attrs->>'brand'.@> tests containment: attrs @> '{"brand": "boAt"}'.?, ?|, ?& test whether keys exist.jsonb_set, || (merge) and - (remove key) modify documents.@? and @@, plus JSON_TABLE added in PostgreSQL 17 to turn JSON into rows.jsonb_ops: supports key existence (?) and containment (@>). Good general choice.jsonb_path_ops: supports @> and jsonpath operators only, but is smaller and usually faster for containment.((attrs->>'brand')): best when you always filter or sort on one known key.CHECK constraints.CREATE TABLE products (
id BIGSERIAL PRIMARY KEY,
category TEXT NOT NULL,
price_paise INTEGER NOT NULL,
attrs JSONB NOT NULL DEFAULT '{}'
);
CREATE INDEX products_attrs_gin ON products USING GIN (attrs jsonb_path_ops);
INSERT INTO products (category, price_paise, attrs) VALUES
('phone', 1499900, '{"brand": "Redmi", "ram_gb": 8, "5g": true}'),
('shirt', 79900, '{"brand": "Allen Solly", "size": "M"}');
-- Containment query can use the GIN index
SELECT id, attrs->>'brand' AS brand
FROM products
WHERE attrs @> '{"5g": true}';
jsonb_path_ops makes @> lookups fast while staying smaller than the default GIN operator class.
-- Generated columns (PG 12+) give real stats and B-tree indexes
ALTER TABLE products
ADD COLUMN brand TEXT GENERATED ALWAYS AS (attrs->>'brand') STORED;
CREATE INDEX products_brand_idx ON products (brand);
-- Update one key without replacing the whole document in SQL
UPDATE products
SET attrs = jsonb_set(attrs, '{ram_gb}', '12')
WHERE id = 1;
A stored generated column keeps the value in sync automatically and gives the planner proper statistics for that key.
JSONB, GIN Index, PostgreSQL, Semi-Structured Data, Containment Operator