This page is not available in every language. Missing translations are disabled in the language selector.

Quick reference

PostgreSQL JSON & JSONB Cheatsheet

A quick reference guide for PostgreSQL JSON and JSONB: extraction operators, containment, existence checks, path modifications, and aggregation functions.

· Published

PostgreSQL provides native support for JSON data via json (stores text as-is) and jsonb (deconstructed binary format supporting GIN indexing and fast lookups).

Extraction Operators

Single arrow (->, #>) returns json/jsonb. Double arrow (->>, #>>) returns text.

SELECT * FROM users WHERE data->>'name' = 'John';
SELECT data->>'name' AS name FROM users;
Operator Left Type Right Type Description Return Type
-> jsonb int Get array element by 0-based index jsonb
-> jsonb text Get object field by key jsonb
#> jsonb text[] Get value at specified path jsonb
->> jsonb int Get array element as text text
->> jsonb text Get object field as text text
#>> jsonb text[] Get value at path as text text

Path Query Examples

-- Extract nested data.address.city as text
SELECT data#>>'{address,city}' FROM customers;

-- Extract second element in items array
SELECT order_info->'items'->>1 FROM orders;

Boolean & Containment Operators (jsonb only)

-- Check if JSON object contains a specific top-level key
SELECT * FROM users WHERE data ? 'email';

-- Check if JSON contains all keys in array
SELECT * FROM users WHERE data ?& array['name', 'email'];

-- Check if JSON contains any key in array
SELECT * FROM users WHERE data ?| array['mobile', 'email'];

-- Containment: Left contains Right
SELECT * FROM users WHERE data @> '{"role": "admin"}'::jsonb;

-- Contained by: Left is contained within Right
SELECT * FROM users WHERE data <@ '{"role": "admin", "active": true}'::jsonb;

Modifying & Updating JSONB Data

Concatenation & Key Deletion

-- Append or update key in jsonb object
UPDATE users SET data = data || '{"active": true}'::jsonb WHERE id = 1;

-- Delete key from object
UPDATE users SET data = data - 'temporary_token' WHERE id = 1;

-- Delete element from array by index
UPDATE users SET tags = tags - 1 WHERE id = 1;

-- Delete nested path
UPDATE users SET data = data #- '{profile,avatar}' WHERE id = 1;

jsonb_set Function

-- Syntax: jsonb_set(target, path, new_value, create_missing)
UPDATE users
SET data = jsonb_set(data, '{contact,phone}', '"555-0199"', true)
WHERE id = 1;

Aggregation & Construction Functions

-- Convert rows to JSON array
SELECT json_agg(u) FROM (SELECT id, name FROM users) u;

-- Build JSON object from key-value pairs
SELECT json_build_object('id', id, 'username', name) FROM users;

-- Expand JSON object to table rows
SELECT * FROM json_each('{"a": 1, "b": 2}');
-- Returns columns: key (text), value (json)

References

Related topics