Sub topic 3
Reading values with `->`, `->>`, `#>` and `#>>`
Prerequisites
This chapter assumes that you know SELECT, WHERE, and basic PostgreSQL types. You should also know that JSON objects contain key-value pairs and JSON arrays contain ordered values. The examples use PostgreSQL's jsonb type.
A JSON value can contain nested objects and arrays:
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, "items": [{"sku": "A1", "qty": 2}, {"sku": "B7", "qty": 1}], "shipping": {"city": "Oslo"}}'),
('Grace', '{"status": "pending", "total": 10.00, "items": [{"sku": "A1", "qty": 1}], "shipping": {"city": "Bergen"}}');Choosing an extraction operator
PostgreSQL provides four closely related operators. The arrow operators navigate one level. The hash-arrow operators navigate through a path containing several keys or array indexes.
| Operator | Result | Path form |
|---|---|---|
| `->` | `jsonb` | One key or array index |
| `->>` | `text` | One key or array index |
| `#>` | `jsonb` | Text-array path |
| `#>>` | `text` | Text-array path |
Use -> or #> when you want to continue navigating the JSON value. Use ->> or #>> when you need ordinary SQL text, such as text for display or a value to cast to numeric or integer.
SELECT
details -> 'shipping' AS shipping_object,
details -> 'shipping' -> 'city' AS city_json,
details -> 'shipping' ->> 'city' AS city_text
FROM orders;The first expression returns a JSON object. The second returns a JSON string value. The third returns the string as SQL text.
Navigating nested objects and arrays
An object key can be supplied as a quoted string. An array element uses a zero-based integer index:
SELECT
customer,
details -> 'items' -> 0 ->> 'sku' AS first_sku,
details -> 'items' -> 1 ->> 'qty' AS second_quantity
FROM orders;For Ada, first_sku is A1 and second_quantity is the text value 1. Grace has only one item, so the second expression returns SQL NULL.
The path operators express the same navigation more compactly:
SELECT
customer,
details #> '{shipping,city}' AS city_json,
details #>> '{shipping,city}' AS city_text,
details #>> '{items,0,sku}' AS first_sku
FROM orders;The path is a PostgreSQL text array. In the literal '{items,0,sku}', PostgreSQL reads items, 0, and sku as successive path steps.
Casting extracted text
JSON numbers are not automatically returned as PostgreSQL numeric values when you use a text-returning operator. Cast the result explicitly:
SELECT
customer,
(details ->> 'total')::numeric AS total,
((details #>> '{items,0,qty}')::int * 2) AS doubled_quantity
FROM orders
WHERE details ->> 'status' = 'paid';The WHERE clause compares text to the text literal 'paid'. The total value becomes a PostgreSQL numeric, and the quantity becomes an integer before multiplication.
A cast can fail if the JSON text is not a valid value for the target SQL type. For example, casting "unknown" to numeric raises an error. Validate or filter data before casting when documents may have inconsistent shapes.
Missing values and JSON null
If a requested key, array index, or path does not exist, these operators return SQL NULL. A JSON document can also contain the JSON value null. The -> family preserves JSON representation, while the text-returning operators are intended for SQL text and commonly produce SQL NULL for a JSON null value.
Use IS NULL to test an extracted result:
SELECT id, customer
FROM orders
WHERE details #>> '{shipping,postal_code}' IS NULL;A missing path is not the same as an empty string. Do not compare it with = NULL; SQL requires IS NULL or IS NOT NULL.
>callout note > Choose the operator based on the next operation. Use -> or #> for more JSON navigation. Use ->> or #>> for comparison, display, or casting to a SQL type.
Exercise
Write a query that returns each customer's name and the city as SQL text, but only for orders whose first item's quantity is greater than 1.
Show answer
SELECT customer, details #>> '{shipping,city}' AS city FROM orders WHERE (details #>> '{items,0,qty}')::int > 1;