SQL course · Module 10: Concurrency · Lesson 35 of 40
Quick answer: PostgreSQL JSONB is a column type that stores JSON in a binary form you can search and index. Read a field with -> (gives jsonb) or ->> (gives text), filter with @> (“contains”) or ? (“has this key”), and change a value with jsonb_set. A GIN index makes @> and ? fast on big tables. PostgreSQL also has arrays such as text[], which you search with = ANY(...) or @> and turn into rows with unnest. Use both for data whose shape changes from row to row, not for data you could keep in normal columns.
In this lesson you will learn:
- the difference between
jsonandjsonb, and why most tables should usejsonb - how to read, search and change JSONB with
->,->>,#>,@>,?,jsonb_setandjsonb_array_elements - how to build JSON from tables with
jsonb_build_objectandjsonb_agg - how a GIN index speeds up JSONB searches, shown with a real plan
- arrays:
ARRAY[],ANY,@>,unnestandarray_agg, and when not to use JSONB or arrays
Before you start: the previous lesson was Lesson 34, Transaction Isolation Levels, Locks and Deadlocks; for this one you need Lesson 16, SQL CREATE TABLE: Data Types and Constraints and Lesson 29, Database Normalization: 1NF, 2NF, 3NF and BCNF With Examples.
We ran every example on PostgreSQL 16.15 with the shop database from Lesson 3 and checked the current PostgreSQL 18 manual. Everything here also works on newer versions. The lesson creates two tables and drops them at the end; the four shop tables do not change. As in earlier lessons, \pset null '(null)' makes NULL visible.
Table of Contents
json vs jsonb
PostgreSQL has two JSON types. The manual says json “stores an exact copy of the input text”, while jsonb is “stored in a decomposed binary format” that is “significantly faster to process” and “also supports indexing” (PostgreSQL docs: JSON Types). The difference is easy to see:
SELECT '{"b": 1, "a": 2, "a": 3}'::json AS as_json,
'{"b": 1, "a": 2, "a": 3}'::jsonb AS as_jsonb;
as_json | as_jsonb
--------------------------+------------------
{"b": 1, "a": 2, "a": 3} | {"a": 3, "b": 1}
(1 row)
json kept the text exactly, with the duplicate key a. jsonb kept only the last value of a and changed the key order. The manual’s advice: “most applications should prefer to store JSON data as jsonb“.
A table with a jsonb column and an array column
Our products have different attributes: a mouse has a DPI value, a lamp has lumens. Instead of many mostly empty columns, we keep these in one jsonb column, plus a text[] array of tags. The values are made-up example data:
CREATE TABLE product_attrs (
product_id integer PRIMARY KEY REFERENCES products (id),
attrs jsonb NOT NULL,
tags text[] NOT NULL DEFAULT '{}'
);
INSERT INTO product_attrs (product_id, attrs, tags) VALUES
(1, '{"color": "black", "wireless": true, "specs": {"dpi": 1600, "battery_hours": 12}}', ARRAY['wireless', 'bestseller']),
(2, '{"color": "white", "wireless": false, "specs": {"switch": "brown", "layout": "US"}, "ports": ["usb-c"]}', ARRAY['gaming']),
(3, '{"color": "grey", "ports": ["usb-c", "usb-a", "hdmi", "sd"], "specs": {"max_watts": 100}}', ARRAY['usb-c', 'travel']),
(4, '{"color": "silver", "material": "aluminium", "specs": {"max_kg": 8}}', ARRAY['ergonomic']),
(5, '{"color": "black", "specs": {"lumens": 450, "dimmable": true}}', '{}'),
(6, '{"color": "blue", "pages": 120, "pack_size": 3}', ARRAY['bestseller']),
(7, '{"colors": ["black", "blue", "red"], "pack_size": 10}', '{}'),
(8, '{"color": "black", "wireless": true, "specs": {"battery_hours": 30, "anc": true}, "ports": ["usb-c"]}', ARRAY['wireless', 'travel']),
(9, '{"color": "black", "material": "mesh", "specs": {"max_kg": 120}}', ARRAY['ergonomic']),
(10, '{"color": "black", "specs": {"resolution": "1080p", "fps": 30}, "ports": ["usb-a"]}', '{}');
INSERT 0 10
Reading JSONB: -> and ->>
-> returns the field as jsonb; ->> returns it as text (PostgreSQL docs: JSON Functions and Operators):
SELECT product_id,
attrs -> 'color' AS color_json,
attrs ->> 'color' AS color_text,
pg_typeof(attrs -> 'color') AS type_1,
pg_typeof(attrs ->> 'color') AS type_2
FROM product_attrs
WHERE product_id IN (1, 2, 3)
ORDER BY product_id;
product_id | color_json | color_text | type_1 | type_2
------------+------------+------------+--------+--------
1 | "black" | black | jsonb | text
2 | "white" | white | jsonb | text
3 | "grey" | grey | jsonb | text
(3 rows)
The quotes show that "black" is still a JSON string. Use ->> to get normal text.
Nested values: #> and #>>, and casting numbers
To go deeper, chain ->, or give a path in braces to #> (jsonb) or #>> (text). An integer after -> picks an array element, counting from 0:
SELECT p.name,
a.attrs -> 'specs' ->> 'battery_hours' AS battery_1,
a.attrs #>> '{specs,battery_hours}' AS battery_2,
a.attrs #> '{specs}' AS specs,
a.attrs -> 'ports' -> 0 AS first_port
FROM product_attrs a
JOIN products p ON p.id = a.product_id
WHERE a.product_id IN (1, 3, 8)
ORDER BY a.product_id;
name | battery_1 | battery_2 | specs | first_port
-----------------------------+-----------+-----------+------------------------------------+------------
Wireless Mouse | 12 | 12 | {"dpi": 1600, "battery_hours": 12} | (null)
USB-C Hub | (null) | (null) | {"max_watts": 100} | "usb-c"
Noise-Cancelling Headphones | 30 | 30 | {"anc": true, "battery_hours": 30} | "usb-c"
(3 rows)
A missing key gives NULL, not an error. ->> always returns text, so cast it before you compare numbers (CAST and :: are from Lesson 8):
SELECT p.name, (a.attrs #>> '{specs,battery_hours}')::integer AS battery_hours
FROM product_attrs a
JOIN products p ON p.id = a.product_id
WHERE (a.attrs #>> '{specs,battery_hours}')::integer >= 12
ORDER BY battery_hours DESC;
name | battery_hours
-----------------------------+---------------
Noise-Cancelling Headphones | 30
Wireless Mouse | 12
(2 rows)
Without the cast, PostgreSQL compares text, and as text '9' > '12' is true.
Searching JSONB: @> and ?
@> asks “does the left JSON contain the right JSON?”. The right side can be nested:
SELECT p.name
FROM product_attrs a
JOIN products p ON p.id = a.product_id
WHERE a.attrs @> '{"color": "black", "specs": {"anc": true}}';
name
-----------------------------
Noise-Cancelling Headphones
(1 row)
? asks whether a key exists at the top level:
SELECT p.name, a.attrs -> 'ports' AS ports
FROM product_attrs a
JOIN products p ON p.id = a.product_id
WHERE a.attrs ? 'ports'
ORDER BY p.name;
name | ports
-----------------------------+----------------------------------
HD Webcam | ["usb-a"]
Mechanical Keyboard | ["usb-c"]
Noise-Cancelling Headphones | ["usb-c"]
USB-C Hub | ["usb-c", "usb-a", "hdmi", "sd"]
(4 rows)
? looks only at the top level: for the mouse, attrs ? 'dpi' was false, while attrs -> 'specs' ? 'dpi' was true.
JSON arrays to rows: jsonb_array_elements
jsonb_array_elements “expands the top-level JSON array into a set of JSON values”; the _text version returns text. Then you can group as usual (Lesson 10):
SELECT port, count(*) AS products
FROM product_attrs a, jsonb_array_elements_text(a.attrs -> 'ports') AS port
GROUP BY port
ORDER BY products DESC, port;
port | products
-------+----------
usb-c | 3
usb-a | 2
hdmi | 1
sd | 1
(4 rows)
Building JSON: jsonb_build_object and jsonb_agg
You can also turn rows into JSON, for example for an API. jsonb_build_object makes an object from key/value pairs, and the aggregate jsonb_agg collects values into one array. Here is order 7 as one document:
SELECT jsonb_pretty(
jsonb_build_object(
'order_id', o.id,
'customer', c.name,
'status', o.status,
'items', jsonb_agg(jsonb_build_object('product', p.name,
'qty', oi.quantity,
'unit_price', oi.unit_price)
ORDER BY p.id)
)
) AS order_json
FROM orders o
JOIN customers c ON c.id = o.customer_id
JOIN order_items oi ON oi.order_id = o.id
JOIN products p ON p.id = oi.product_id
WHERE o.id = 7
GROUP BY o.id, c.name, o.status;
order_json
--------------------------------------------
{ +
"items": [ +
{ +
"qty": 1, +
"product": "Wireless Mouse", +
"unit_price": 22.99 +
}, +
{ +
"qty": 2, +
"product": "Gel Pens 10-Pack",+
"unit_price": 6.75 +
}, +
{ +
"qty": 1, +
"product": "HD Webcam", +
"unit_price": 54.90 +
} +
], +
"status": "delivered", +
"customer": "NOAH WILSON", +
"order_id": 7 +
}
(1 row)
jsonb_pretty adds line breaks, which psql marks with +. The items follow ORDER BY p.id, but the keys come out in jsonb’s own order.
Changing JSONB: jsonb_set, || and –
jsonb_set(target, path, new_value) replaces the value at a path. || merges in new keys and - removes a key:
UPDATE product_attrs
SET attrs = jsonb_set(attrs, '{specs,battery_hours}', '14')
WHERE product_id = 1
RETURNING attrs;
attrs
-----------------------------------------------------------------------------------
{"color": "black", "specs": {"dpi": 1600, "battery_hours": 14}, "wireless": true}
(1 row)
UPDATE 1
attrs || '{"on_sale": true}' added the key on_sale, and attrs - 'on_sale' took it away again (both are in lesson35.sql). Note that the update writes the whole row again: the manual warns that “any update acquires a row-level lock on the whole row” (row locks were in Lesson 34).
PostgreSQL JSONB indexing with GIN
A normal B-tree index (Lesson 31) cannot answer “which documents contain this?”. A GIN index can. The default GIN class for jsonb supports ?, ?|, ?&, @>, @? and @@. We filled a demo table, attrs_demo, with 20,000 made-up rows (the CREATE TABLE and INSERT ... generate_series are in lesson35.sql) and ran EXPLAIN ANALYZE (Lesson 32) before and after the index:
EXPLAIN (ANALYZE, COSTS OFF)
SELECT id FROM attrs_demo WHERE attrs @> '{"sku": 12345}';
Seq Scan on attrs_demo (actual time=3.009..4.448 rows=1 loops=1)
Filter: (attrs @> '{"sku": 12345}'::jsonb)
Rows Removed by Filter: 19999
Planning Time: 0.154 ms
Execution Time: 4.465 ms
CREATE INDEX attrs_demo_attrs_gin ON attrs_demo USING GIN (attrs);
Bitmap Heap Scan on attrs_demo (actual time=0.086..0.086 rows=1 loops=1)
Recheck Cond: (attrs @> '{"sku": 12345}'::jsonb)
Heap Blocks: exact=1
-> Bitmap Index Scan on attrs_demo_attrs_gin (actual time=0.077..0.078 rows=1 loops=1)
Index Cond: (attrs @> '{"sku": 12345}'::jsonb)
Planning Time: 0.178 ms
Execution Time: 0.105 ms
The scan of all 20,000 rows became an index lookup. The times are from one run on our test machine; your times will differ, so compare the plan shapes, not the milliseconds. The same question written as attrs ->> 'sku' = '12345' still gave Seq Scan on attrs_demo: this GIN index does not support ->>, so write the filter with @>.

Arrays: ARRAY[], ANY, @>, unnest and array_agg
A PostgreSQL array holds several values of one type in one column. Write it as ARRAY['a', 'b'] or as the text '{a,b}'. Search one element with = ANY (...), or several with @>; array_append(tags, 'new') adds one element at the end (PostgreSQL docs: Array Functions and Operators):
SELECT p.name, a.tags
FROM product_attrs a
JOIN products p ON p.id = a.product_id
WHERE 'wireless' = ANY (a.tags)
ORDER BY p.name;
name | tags
-----------------------------+-----------------------
Noise-Cancelling Headphones | {wireless,travel}
Wireless Mouse | {wireless,bestseller}
(2 rows)
WHERE a.tags @> ARRAY['wireless', 'travel'] returned only the headphones. Array positions start at 1, and a position outside the array gives NULL (PostgreSQL docs: Arrays):
SELECT product_id, tags, tags[1] AS first_tag, tags[3] AS third_tag, cardinality(tags) AS n_tags
FROM product_attrs
WHERE product_id IN (1, 3, 5)
ORDER BY product_id;
product_id | tags | first_tag | third_tag | n_tags
------------+-----------------------+-----------+-----------+--------
1 | {wireless,bestseller} | wireless | (null) | 2
3 | {usb-c,travel} | usb-c | (null) | 2
5 | {} | (null) | (null) | 0
(3 rows)
unnest turns an array into rows, one row per element, so you can count tags:
SELECT tag, count(*) AS products
FROM product_attrs, unnest(tags) AS tag
GROUP BY tag
ORDER BY products DESC, tag;
tag | products
------------+----------
bestseller | 2
ergonomic | 2
travel | 2
wireless | 2
gaming | 1
usb-c | 1
(6 rows)
array_agg does the opposite and collects rows into an array:
SELECT category, array_agg(name ORDER BY name) AS product_names
FROM products
GROUP BY category
ORDER BY category;
category | product_names
-------------+------------------------------------------------------------------------------------------------
Accessories | {"Laptop Stand"}
Electronics | {"HD Webcam","Mechanical Keyboard","Noise-Cancelling Headphones","USB-C Hub","Wireless Mouse"}
Home Office | {"Desk Lamp","Ergonomic Chair"}
Stationery | {"Gel Pens 10-Pack","Notebook Pack"}
(4 rows)
SQL/JSON functions in newer PostgreSQL versions
PostgreSQL also has the SQL-standard JSON functions. Version 16 added JSON_ARRAY(), JSON_ARRAYAGG(), JSON_OBJECT(), JSON_OBJECTAGG() and the IS JSON checks (PostgreSQL 16 release notes), so they ran on our server:
SELECT JSON_OBJECT('sku': 1, 'color': 'black') AS obj,
JSON_ARRAY('usb-c', 'hdmi') AS arr,
'{"a": 1}' IS JSON OBJECT AS is_obj,
'[1, 2' IS JSON AS is_valid;
obj | arr | is_obj | is_valid
--------------------------------+-------------------+--------+----------
{"sku" : 1, "color" : "black"} | ["usb-c", "hdmi"] | t | f
(1 row)
JSON_TABLE(), JSON_EXISTS(), JSON_QUERY() and JSON_VALUE() came in PostgreSQL 17 (PostgreSQL 17 release notes). JSON_TABLE turns JSON into rows and columns inside FROM. On our 16.15 server, JSON_QUERY failed with function json_query(jsonb, unknown) does not exist, so we do not show them here. If you have PostgreSQL 17 or newer, see the manual.
When not to use JSONB or arrays
JSONB is not a way to skip table design. If every product has a value, if you join on it, or if it needs a foreign key or a CHECK rule, make it a normal column or a separate table, as in Lesson 29. An array of ids is the same repeating group that first normal form removes. The arrays page gives a direct tip: “Arrays are not sets; searching for specific array elements can be a sign of database misdesign. Consider using a separate table with a row for each item that would be an array element.” For JSON, the manual suggests “limiting JSON documents to a manageable size”. A good use is optional details that differ from row to row and that you mostly read as a whole.
Try it yourself
Run the CREATE TABLE and INSERT from lesson35.sql first.
Exercise 1: Black products and their battery life
List the name and battery_hours of every product whose attrs contain "color": "black". Use @>.
Exercise 2: Add a tag
Add the tag sale to product 5 with array_append, and return the new tags.
Exercise 3: Stationery as JSON
Return all Stationery products as one JSON array of objects with name and price, cheapest first.
Solutions
Solution 1
SELECT p.name, a.attrs #>> '{specs,battery_hours}' AS battery_hours
FROM product_attrs a
JOIN products p ON p.id = a.product_id
WHERE a.attrs @> '{"color": "black"}'
ORDER BY p.name;
name | battery_hours
-----------------------------+---------------
Desk Lamp | (null)
Ergonomic Chair | (null)
HD Webcam | (null)
Noise-Cancelling Headphones | 30
Wireless Mouse | 14
(5 rows)
Products without the key get NULL. The mouse shows 14 because we changed it with jsonb_set earlier.
Solution 2
UPDATE product_attrs
SET tags = array_append(tags, 'sale')
WHERE product_id = 5
RETURNING product_id, tags;
product_id | tags
------------+--------
5 | {sale}
(1 row)
UPDATE 1
Product 5 had an empty array, so it now has one tag.
Solution 3
SELECT jsonb_agg(jsonb_build_object('name', name, 'price', price) ORDER BY price) AS stationery
FROM products
WHERE category = 'Stationery';
stationery
------------------------------------------------------------------------------------------
[{"name": "Gel Pens 10-Pack", "price": 6.75}, {"name": "Notebook Pack", "price": 12.50}]
(1 row)
ORDER BY inside jsonb_agg sets the order of the array elements.
When you finish, run DROP TABLE attrs_demo; and DROP TABLE product_attrs;.
Common mistakes
- Comparing
->with plain text.WHERE attrs -> 'color' = 'black'givesERROR: invalid input syntax for type jsonwithDETAIL: Token "black" is invalid.Useattrs ->> 'color' = 'black'. - Using
@>on ajsoncolumn.json @> jsongivesERROR: operator does not exist: json @> json. Storejsonb. - A dotted path in jsonb_set.
jsonb_set(attrs, 'specs.dpi', '1800')givesERROR: malformed array literal: "specs.dpi". The path is a text array:'{specs,dpi}'. - Comparing numbers as text.
->>returns text, and'9' > '12'is true. Cast first:(attrs ->> 'n')::integer. - Using PostgreSQL 17 functions on version 16.
JSON_QUERYgivesfunction json_query(jsonb, unknown) does not exist, andJSON_TABLEgivessyntax error at or near "COLUMNS". Check your version withSELECT version();.
Frequently asked questions
Should I use json or jsonb in PostgreSQL?
Use jsonb in almost all cases. It is faster to query, supports GIN indexes and has more operators, such as @> and ?. Choose json only when you must keep the exact input text, for example the original key order or duplicate keys.
How do I query a JSON field in PostgreSQL?
Use ->> for a text value (attrs ->> 'color'), #>> for a nested path (attrs #>> '{specs,battery_hours}') and @> to filter by a piece of JSON (attrs @> '{"wireless": true}'). Cast the text when you compare numbers or dates.
Is PostgreSQL JSONB a replacement for MongoDB?
For many apps that need some flexible fields next to normal tables, JSONB is enough, and you keep joins, transactions and constraints in one database. The course hub suggests learning SQL first and a document database later if your work needs it.
Summary
jsonbstores JSON in a binary form that is fast to query and can be indexed; prefer it overjson.->returns jsonb,->>returns text, and#>and#>>follow a path; cast text before comparing numbers.@>(contains) and?(key exists) search JSONB, and a GIN index makes them fast;->>filters do not use that index.jsonb_build_object,jsonb_aggandjsonb_setbuild and change JSON;jsonb_array_elementsandunnestturn arrays into rows.- Use JSONB and arrays for flexible details, not instead of normalized tables.
Next lesson
Next: Lesson 36, Preventing SQL Injection: Parameterized Queries, Roles and GRANT.
Sources
- PostgreSQL documentation: JSON Types (json vs jsonb, containment, GIN indexing)
- PostgreSQL documentation: JSON Functions and Operators
- PostgreSQL documentation: Arrays
- PostgreSQL documentation: Array Functions and Operators
- PostgreSQL 16 release notes (SQL/JSON constructors and IS JSON)
- PostgreSQL 17 release notes (JSON_TABLE, JSON_QUERY, JSON_VALUE, JSON_EXISTS)





