How to use JSONB in PostgreSQL
· Category: SQL & Databases
Short answer
JSONB is a binary JSON storage format in PostgreSQL that supports indexing, advanced querying, and efficient updates compared to plain JSON.
Steps
- Create a JSONB column:
CREATE TABLE logs (id SERIAL PRIMARY KEY, data JSONB); - Insert JSONB:
INSERT INTO logs (data) VALUES ('{\"level\": \"error\"}'); - Query with operators:
SELECT * FROM logs WHERE data @> '{\"level\": \"error\"}'; - Extract values:
SELECT data->>'level' FROM logs; - Create a GIN index:
CREATE INDEX idx_logs_data ON logs USING GIN (data);
Tips
- Use
jsonb_path_existsandjsonb_path_queryfor advanced path-based queries. - Update specific keys with
jsonb_setwithout rewriting the entire document.
Common issues
- Large JSONB values increase table and index bloat.
JSONBdoes not preserve key order or duplicate keys, unlikeJSON.r