Video in progress
When do you use JSONB, and what indexes do you put on it?
JSONB is good for extra attributes whose structure varies or doesn't fit a table. For @> search over the whole document you put a GIN index, and for search on one specific field an expression B-tree index.
📖 Answer
Example: products have different properties depending on category (memory on a phone, size on clothing). Making a column for each makes no sense, and an EAV table makes the queries awful.
CREATE TABLE product (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
name text NOT NULL,
attrs jsonb NOT NULL DEFAULT '{}'
);
-- searching inside the document: containment
SELECT * FROM product WHERE attrs @> '{"color": "qora", "ram": 8}';
CREATE INDEX idx_product_attrs ON product USING gin (attrs jsonb_path_ops);
-- equality or a range on a single field
SELECT * FROM product WHERE (attrs->>'brand') = 'Samsung';
CREATE INDEX idx_product_brand ON product ((attrs->>'brand'));
jsonb_path_ops is smaller than the default jsonb_ops and faster for @>, but it doesn't support the ? (does the key exist) operator.
When I don't use JSONB:
- the field is present in every row and always filtered on: make it a regular column, so the statistics and types are clear;
- the field is a reference to another table: there are no FKs inside JSON;
- the document is often partially updated: every
UPDATErewrites the whole JSONB value.
The difference between json and jsonb: json stores the text unchanged and re-parses it every time, while jsonb stores a binary form and can be indexed. You almost always want jsonb.
Sign up to mark studied questions and save your progress.