Sub topic 3
Reading values with ->, ->>, #> and #>>
This chapter covers the four operators that read values out of json and jsonb documents, how they differ in return type, and the errors people hit when they cast the results. It assumes you can write basic SQL (SELECT, WHERE, JOIN), know JSON syntax, and have a PostgreSQL instance, version 12 or later. Subscripting is covered near the end and needs PostgreSQL 14 or later.
The working model
Every access operator takes a JSON value on the left and a path step on the right. The result is either another JSON value or plain text. That one choice decides what you can do next:
- Operators that return JSON (
->and#>) let you keep navigating deeper. - Operators that return text (
->>and#>>) end the navigation. You then cast the text to a SQL type such asnumeric,int, orboolean.
| Operator | Right operand | Returns | Typical use |
|---|---|---|---|
| `->` | text key or integer index | `json` / `jsonb` | Step into an object or array and keep going |
| `->>` | text key or integer index | `text` | Take a final value and cast it |
| `#>` | text array path | `json` / `jsonb` | Jump several levels in one step |
| `#>>` | text array path | `text` | Jump several levels and get text |
The operators work on both json and jsonb. The result type matches the input type. On a jsonb column, -> returns jsonb.
Sample data
The examples use the orders table from the earlier chapters. Run this first if you have not already:
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"}}');Object keys with -> and ->>
With a text value on the right, -> looks up a key in a JSON object. If the key does not exist, the result is SQL NULL, not an error.
SELECT id,
details -> 'status' AS status_json,
details ->> 'status' AS status_text
FROM orders;For Ada, status_json is the JSON string "paid", shown with double quotes. status_text is the SQL text paid, with no quotes. The quotes are the visible sign that the first value is still JSON.
This matters in a WHERE clause. The comparison below finds nothing, because the left side is jsonb and the right side is parsed as a jsonb literal only if it is valid JSON:
-- Compares jsonb to jsonb. 'paid' is not valid JSON, so this raises an error.
SELECT id FROM orders WHERE details -> 'status' = 'paid';You have two correct choices:
-- Compare as text:
SELECT id FROM orders WHERE details ->> 'status' = 'paid';
-- Or compare as jsonb, with a JSON string literal:
SELECT id FROM orders WHERE details -> 'status' = '"paid"';The first form is the one most people use because it reads naturally.
Chaining and casting
Chain -> to move through nested objects, and finish with ->> to get text. Then cast.
SELECT id,
details -> 'shipping' ->> 'city' AS city,
(details ->> 'total')::numeric AS total
FROM orders
WHERE details ->> 'status' = 'paid';Note the parentheses around details ->> 'total' before ::numeric. The cast operator :: binds more tightly than ->>. Without parentheses, PostgreSQL tries to cast the string literal 'total' to numeric and fails.
-- Wrong: casts 'total' to numeric first
SELECT details ->> 'total'::numeric FROM orders;
-- ERROR: invalid input syntax for type numeric: "total"The same rule applies to ::int, ::boolean, ::timestamptz, and every other cast.
Why cast at all
The result of ->> is text. Text compares and sorts alphabetically, not numerically. Consider:
SELECT id FROM orders ORDER BY details ->> 'total';If one total were 9 and another 10, the text '10' sorts before '9'. Cast first and the ordering is numeric:
SELECT id, (details ->> 'total')::numeric AS total
FROM orders
ORDER BY total DESC;JSON null versus SQL NULL
JSON has its own null. The two operators treat it differently:
->returns a JSONnullvalue, which is a realjsonbvalue and is not SQLNULL.->>returns SQLNULL.
A missing key gives SQL NULL from both operators. So ->> cannot tell a missing key apart from a key set to null. If you need to tell them apart, test with the existence operator ? from the next chapter, or compare with jsonb_typeof:
SELECT jsonb_typeof('{"a": null}'::jsonb -> 'a') AS present_null,
jsonb_typeof('{"a": null}'::jsonb -> 'b') AS missing_key;The first column is the text null. The second is SQL NULL, because '{"a": null}'::jsonb -> 'b' yields SQL NULL.
Array elements by index
With an integer on the right, -> and ->> read an array element. Indexes start at zero.
SELECT id,
details -> 'items' -> 0 ->> 'sku' AS first_sku,
(details -> 'items' -> 0 ->> 'qty')::int AS first_qty
FROM orders;Negative integers count from the end, so -1 is the last element:
SELECT id, details -> 'items' -> -1 ->> 'sku' AS last_sku
FROM orders;Ada has two items, so her last_sku is B7. Grace has one, so hers is A1.
An index past the end of the array returns SQL NULL. Applying an integer to an object, or a text key to an array, also returns NULL rather than raising an error. This is convenient for messy data, and it hides typos. If a result column is unexpectedly empty, check that each step matches the shape of the document at that point.
Paths with #> and #>>
When the path is deep, a long chain of -> is noisy. The #> and #>> operators take a text array that lists every step. Integers inside the array are written as text, such as '0', and PostgreSQL uses them as array indexes when the current value is an array.
SELECT id,
details #> '{shipping,city}' AS city_json,
details #>> '{shipping,city}' AS city_text,
details #>> '{items,0,sku}' AS first_sku
FROM orders;These are equivalent to details -> 'shipping' -> 'city', details -> 'shipping' ->> 'city', and details -> 'items' -> 0 ->> 'sku'.
The path form is useful in two situations:
- The path is stored or built at run time. You can pass a parameter, or build an array with
ARRAY['items', '0', 'sku']. - You want one expression instead of several, such as when you pass the same path to a function like
jsonb_setlater.
SELECT details #>> ARRAY['items', '0', 'sku'] AS first_sku
FROM orders;As with ->, a path that does not exist returns SQL NULL.
Choosing between them
Subscripting in PostgreSQL 14 and later
From PostgreSQL 14, jsonb also supports subscript syntax, which looks like array access in other languages:
SELECT id,
details['shipping']['city'] AS city_json,
details['items'][0]['sku'] AS first_sku_json
FROM orders;Subscripting always returns jsonb, not text, so it behaves like ->. To get text, cast the result or use ->>. You can use a cast on a string result: details['status'] #>> '{}' extracts the scalar string as text.
SELECT details['status'] #>> '{}' AS status_text
FROM orders;Subscripting is most useful in UPDATE ... SET details['status'] = '"shipped"', covered in a later chapter. For reading, the operators work on all supported versions, so they are the safer default in code that must run on older servers. Subscripting applies only to jsonb, not to json.
json versus jsonb at read time
The operators give the same answers on both types for simple lookups. The difference is in cost and in duplicate keys:
jsonstores the original text. Each access operator re-parses the whole value. Deep or repeated access on large documents is slower.jsonbstores a parsed binary form, so lookups are faster, and duplicate keys are collapsed to the last value at insert time.- With
json, a document such as{"a": 1, "a": 2}is kept as written, and->returns the last value,2.
For anything you query often, jsonb is the usual choice.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `invalid input syntax for type json` in a `WHERE` | Comparing `->` output to an unquoted string | Use `->>` or compare to `'"paid"'` |
| `invalid input syntax for type numeric: "total"` | Missing parentheses before `::numeric` | Write `(details ->> 'total')::numeric` |
| `invalid input syntax for type integer: "12.5"` | Casting a decimal string to `int` | Cast to `numeric`, then round or cast again |
| Result column is all `NULL` | Wrong key, wrong case, or wrong nesting level | Inspect with `SELECT details FROM orders LIMIT 1` and match each step |
| `operator does not exist: text -> unknown` | The column is `text`, not `json` or `jsonb` | Cast: `details::jsonb -> 'status'` |
| Numeric sort is wrong | Sorting `->>` text | Cast before `ORDER BY` |
A cast failure on one bad row fails the whole query. If the column holds mixed data, filter with jsonb_typeof in the same query before you cast. PostgreSQL does not guarantee the order in which it evaluates WHERE conditions, so for strict safety use a CASE expression:
SELECT id,
CASE WHEN jsonb_typeof(details -> 'total') = 'number'
THEN (details ->> 'total')::numeric
END AS total
FROM orders;Summary of behavior
->and#>return JSON.->>and#>>return text.- Missing keys, out-of-range indexes, and mismatched shapes give SQL
NULL, not errors. ->>returns SQLNULLfor a JSONnull.->returns a JSONnull.- Wrap
->>expressions in parentheses before casting. - Array indexes start at 0, and negative indexes count from the end.
Exercise
Write a query that returns each order's id and the quantity of its last item as an integer, for orders whose shipping city is Oslo. Why is the first argument to the cast wrapped in parentheses?
Show answer
SELECT id, (details -> 'items' -> -1 ->> 'qty')::int AS last_qty FROM orders WHERE details #>> '{shipping,city}' = 'Oslo'; The parentheses are needed because :: binds more tightly than ->>. Without them, PostgreSQL would try to cast the literal 'qty' to int instead of the extracted value.
Exercise
A row has details = '{"coupon": null}'. What do details -> 'coupon', details ->> 'coupon', and details ->> 'discount' return, and how can you tell the first and third cases apart in a query?
Show answer
details -> 'coupon' returns the JSON value null (a jsonb value, not SQL NULL). details ->> 'coupon' returns SQL NULL. details ->> 'discount' returns SQL NULL because the key is missing. To tell a JSON null from a missing key, use details ? 'coupon' (true only if the key exists) or jsonb_typeof(details -> 'coupon') (returns the text 'null' for a JSON null and SQL NULL for a missing key).
Exercise
Rewrite details -> 'items' -> 0 ->> 'sku' using a single path operator, then with PostgreSQL 14 subscripting that returns text.
Show answer
Path operator: details #>> '{items,0,sku}'. Subscripting returns jsonb, so extract the text with #>> '{}': details['items'][0]['sku'] #>> '{}'.