PostgreSQL JSONB
PostgreSQL can store JSON documents inside a column and query them with SQL. The jsonb type stores JSON in a parsed, binary form: it is fast to search, can be indexed, and removes duplicate keys and insignificant whitespace. (The older json type keeps the text exactly as written; prefer jsonb.)
In the sample data, books.details is a jsonb column:
SELECT id, title, details FROM books WHERE id IN (3, 11); id | title | details
----+--------------------+--------------------------------------------------------------------------------------------------------
3 | Signal from Kepler | {"pages": 401, "format": "hardcover", "series": {"name": "Deep Sky", "part": 2}, "language": "en"}
11 | Empires of Sand | {"pages": 540, "awards": ["History Prize", "Readers Choice"], "format": "hardcover", "language": "en"}
(2 rows)
Reading values: -> and ->>
| Operator | Returns | Example |
|---|---|---|
-> |
a JSON value (jsonb) |
details -> 'series' |
->> |
the value as text | details ->> 'format' |
#> / #>> |
follow a path (json / text) | details #>> '{series,name}' |
-> 0 |
array element by position | details -> 'awards' -> 0 |
SELECT title,
details ->> 'format' AS format,
(details ->> 'pages')::integer AS pages,
details #>> '{series,name}' AS series,
details -> 'awards' ->> 0 AS first_award
FROM books
WHERE id IN (1, 3, 5, 11); title | format | pages | series | first_award
--------------------+-----------+-------+----------+------------------
The Salt Road | paperback | 312 | |
Signal from Kepler | hardcover | 401 | Deep Sky |
Clockwork Garden | hardcover | 288 | | Nebula Shortlist
Empires of Sand | hardcover | 540 | | History Prize
(4 rows)
Missing keys simply give NULL. Values extracted with ->> are text, so cast them before doing arithmetic or numeric comparisons.
Filtering on JSON
-- Hardcovers with more than 300 pages
SELECT title, details ->> 'pages' AS pages
FROM books
WHERE details ->> 'format' = 'hardcover'
AND (details ->> 'pages')::int > 300;
-- Containment: does the document include these key/value pairs?
SELECT title FROM books WHERE details @> '{"language": "bg"}';
-- Does a key exist?
SELECT title FROM books WHERE details ? 'awards'; title | pages
----------------------+-------
Signal from Kepler | 401
Postgres in Practice | 512
Empires of Sand | 540
(3 rows)
title
-----------------
Paper Lanterns
Winter in Sofia
(2 rows)
title
------------------
Clockwork Garden
Empires of Sand
(2 rows)
The containment operator @> and the key-exists operator ? can use a GIN index: CREATE INDEX ON books USING gin (details);.
Building JSON
Functions turn rows into JSON, useful for APIs:
SELECT jsonb_build_object('id', b.id, 'title', b.title, 'author', a.name, 'price', b.price) AS book_json
FROM books b JOIN authors a ON a.id = b.author_id
WHERE b.id = 7;
SELECT jsonb_agg(title ORDER BY title) AS titles FROM books WHERE category_id = 2;
SELECT to_jsonb(c) - 'email' - 'joined' AS customer FROM customers c WHERE id = 1; book_json
-----------------------------------------------------------------------------------
{"id": 7, "price": 13.49, "title": "The Quiet Witness", "author": "Daniel Reyes"}
(1 row)
titles
--------------------------------------------------------------
["Clockwork Garden", "Signal from Kepler", "The Last Orbit"]
(1 row)
customer
-------------------------------------------------------------------------------------------------
{"id": 1, "city": "Warsaw", "country": "Poland", "last_name": "Kowalski", "first_name": "Anna"}
(1 row)
to_jsonb converts a whole row into an object, and the - operator removes keys from it.
Changing JSON
|| merges objects (the right side wins), jsonb_set replaces a value at a path, and - deletes a key:
UPDATE books
SET details = details || '{"signed": true}'
WHERE id = 9;
UPDATE books
SET details = jsonb_set(details, '{pages}', '530')
WHERE id = 9;
UPDATE books
SET details = details - 'language'
WHERE id = 9;
SELECT details FROM books WHERE id = 9;UPDATE 1
UPDATE 1
UPDATE 1
details
-------------------------------------------------------
{"pages": 530, "format": "hardcover", "signed": true}
(1 row)
Expanding JSON into rows
jsonb_each turns an object into key/value rows; jsonb_array_elements_text turns an array into rows. Here every award becomes its own row:
SELECT b.title, award
FROM books b
CROSS JOIN LATERAL jsonb_array_elements_text(b.details -> 'awards') AS award
ORDER BY b.title, award;
SELECT key, value FROM books, jsonb_each(details) WHERE id = 4 ORDER BY key; title | award
------------------+------------------
Clockwork Garden | Nebula Shortlist
Empires of Sand | History Prize
Empires of Sand | Readers Choice
(3 rows)
key | value
----------+---------------------------------
format | "paperback"
language | "en"
pages | 356
series | {"name": "Deep Sky", "part": 1}
(4 rows)
SQL/JSON path
PostgreSQL also supports the standard SQL/JSON path language for more complex searches:
SELECT title,
jsonb_path_query_first(details, '$.series.part') AS part
FROM books
WHERE jsonb_path_exists(details, '$.series ? (@.name == "Deep Sky")')
ORDER BY part; title | part
--------------------+------
The Last Orbit | 1
Signal from Kepler | 2
(2 rows)
Tip: JSONB is great for flexible, optional attributes (like book details). Data you filter, join or constrain on all the time usually belongs in regular columns, where types, foreign keys and
NOT NULLprotect it.
Test yourself
What is the difference between -> and ->>?
- None
->returns jsonb,->>returns text->>follows a path->only works on arrays
Which condition finds documents containing the pair "format": "ebook"?
- details = 'ebook'
- details @> '{"format": "ebook"}'
- details ? 'ebook'
- details -> 'ebook'
Why is jsonb usually preferred over json?
- It keeps the original formatting
- It is stored parsed, supports indexing and is faster to query
- It allows duplicate keys
- It is smaller text