Sub topic 1
json versus jsonb: how each type stores data
Prerequisites
This chapter assumes you know basic SQL (SELECT, INSERT, WHERE), can create a table with CREATE TABLE, and have access to a PostgreSQL 12 or later instance. You should also be comfortable reading JSON objects, arrays, and string values.
PostgreSQL offers two JSON types. The json type stores the exact text you give it. The jsonb type (binary JSON) parses the text on input and stores a decoded binary form. This difference affects storage, speed, and what the database remembers about your document.
SELECT '{"b": 1, "a": 2, "a": 3}'::json AS as_json,
'{"b": 1, "a": 2, "a": 3}'::jsonb AS as_jsonb;The json result keeps the original text, including duplicate keys and key order. The jsonb result keeps only the last value for a duplicate key, and it sorts keys. Use jsonb for most work. It supports indexing and faster reads, and it is the type this tutorial uses.
Storing JSON in a table and writing JSON literals
A JSON literal is a quoted string that PostgreSQL converts to the target type. Create a table and insert two rows:
CREATE TABLE orders (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
customer text NOT NULL,
details jsonb NOT NULL
);
INSERT INTO orders (customer, details) VALUES
('Ada', '{"status": "paid", "total": 42.50, "shipping": {"city": "Oslo"}}'),
('Grace', '{"status": "pending", "total": 10.00, "shipping": {"city": "Bergen"}}');Reading values with ->, ->>, #> and #>>
Four operators extract values:
->returns a JSON value for a key or array index. Its result can be chained.->>returns the value astext. Cast it when you need a number.#>takes a path array and returns JSON.#>>takes a path array and returnstext.
SELECT id,
details -> 'shipping' ->> 'city' AS city,
(details ->> 'total')::numeric AS total
FROM orders
WHERE details ->> 'status' = 'paid';
SELECT details #>> '{shipping,city}' AS city
FROM orders;The first query returns one row: id 1, city Oslo, total 42.50. The second returns Oslo and Bergen.
flowchart TD
A[JSON text literal] --> B{Column type}
B -->|json| C[Stores exact text]
B -->|jsonb| D[Stores parsed binary form]
D --> E[Indexable and faster to read]caption: How json and jsonb store the same input alt: A text literal branches into json, which keeps exact text, and jsonb, which keeps a parsed binary form that can be indexed.
> Note: ->> always returns text, so details ->> 'total' > 10 compares strings. Cast first with (details ->> 'total')::numeric.
Exercise
Using the orders table, write a query that returns the customer and the shipping city for the row where the path shipping.city is Bergen.
Show answer
SELECT customer, details #>> '{shipping,city}' AS city FROM orders WHERE details #>> '{shipping,city}' = 'Bergen';