PostgreSQL JSONB: Native JSON in a Relational Database
PostgreSQL's JSONB type stores JSON in a decomposed binary format that supports indexing, querying with operators, and full SQL JOIN capabilities.
JSONB vs JSON Type
- JSONB (recommended): Binary storage, supports indexing, slightly slower writes.
- JSON: Text storage, preserves whitespace and key order, no indexing.
Key Operators
-> 'key'— Extract JSON object field (returns JSON).->> 'key'— Extract JSON field as text (returns TEXT).#> '{a,b}'— Extract nested path (returns JSON).@> '{}'— Contains operator (supports GIN index).
-- Create table with JSONB column
CREATE TABLE orders (
id SERIAL PRIMARY KEY,
customer_id INTEGER NOT NULL,
payload JSONB NOT NULL,
created_at TIMESTAMPTZ DEFAULT NOW()
);
-- Insert JSON data
INSERT INTO orders (customer_id, payload)
VALUES (101, '{"product":"Widget A","qty":5,"price":49.99,"tags":["sale"]}');
-- Query: extract specific field as text
SELECT payload->>'product' AS product_name FROM orders;
-- Query: filter by nested JSON value
SELECT * FROM orders WHERE payload->>'product' = 'Widget A';
-- Query: contains operator (use GIN index for performance)
SELECT * FROM orders WHERE payload @> '{"tags":["sale"]}';
-- Create GIN index for fast JSONB queries
CREATE INDEX idx_orders_payload ON orders USING GIN (payload);