JSON in a Cell

Extracting a value: -> and ->>

32 min

The commandant flips through the documents you arranged in a stack and sets them aside. He doesn’t have time to read every parcel in full. For the report, he needs individual values: which products people viewed, at what price, and which cities the buyers came from.

You open event 4. On February 11, buyer 17 views “Plush Cat Toy” in app version 3.9.2. The document contains the price, "price": "12.90", but it is in quotes. The next morning, buyer 42 views the book “SQL for Pros” in app version 4.6.0, and event 6 contains the same amount without quotes: "price": 12.90.

The price is the same: $12.90. The representation is different. PostgreSQL treats them as two different things.

QUERY: You don’t need to unpack the whole parcel just to get one price. Find the right box by its label and take out only that one.

Here, the label is the key. PostgreSQL has two arrow operators for extracting a value by key. They differ by a single character, but they return different types, which changes how later comparisons behave.

A cadet, seen from behind, stands at the Unpacking Room table and reaches toward a holographic amber box. One small glowing box rises from it on a thin beam of light while the others remain closed inside. Two identical small boxes sit nearby on the table: one is wrapped in a transparent glowing shell, while the other is bare. QUERY, the robot cat, holds the edge of the large box with one paw and watches the raised box.
One arrow extracts the value from the document. Two arrows also remove its JSON wrapper.

The -> arrow: extract a value by key

Take event 1, the headphone view. You saw its payload in the previous lesson: the keys app, user, price, product_id, schema_version.

Read payload -> 'price' literally: take the document from payload, find the price key, and return the value stored under it. For event 1, that gives 59.90. And payload -> 'user' returns the entire nested object {"id": 23, "city": "Tampa"}. The size of the value does not matter: the arrow extracts whatever is stored under the specified key.

After a single arrow, the result is still of type jsonb. Imagine taking a small box out of a larger one without opening its lid. If the value inside was a string, it remains a JSON string, including its double quotes.

Write the key as a string in single quotes, just like ordinary text in SQL: 'price'. Case matters, so 'Price' and 'price' are different keys. A missing key returns NULL without an error. We’ll work with those cases separately in the third lesson.

In the cell below, the arrow extracts three values from three events, and the last column shows the type it returned. The output is shown exactly as PostgreSQL displays it: JSON strings keep their quotes. Before you run the query, predict what you’ll see in the app column for all three events: with quotes or without? And what about price?

SELECT event_id,
       payload -> 'app' AS app,
       payload -> 'price' AS price,
       payload -> 'user' AS user_doc,
       pg_typeof(payload -> 'price') AS arrow_type
FROM app_events
WHERE event_id IN (1, 6, 8)
ORDER BY event_id;

The ->> double arrow: extract text

The ->> operator also finds a value by key, but it returns ordinary text of type text. A string loses its quotes: "4.6.0" becomes 4.6.0. The JSON number 59.90 becomes text made up of four digits. Even a nested object becomes text that looks like JSON, although SQL now treats it as a string of characters.

Return to the two parcels from the start of the lesson. In event 4, the price is stored as the JSON string "12.90"; in event 6, it is the JSON number 12.90. We can already predict event 4. The single arrow returns jsonb containing a string, so the quotes remain in the output: "12.90". The double arrow removes them, giving the text 12.90.

Now consider event 6. What will each arrow return? Compare the arrow and double_arrow columns for the two events before you run the query.

SELECT event_id,
       (payload -> 'price')::text AS arrow,
       payload ->> 'price' AS double_arrow,
       pg_typeof(payload ->> 'price') AS double_type
FROM app_events
WHERE event_id IN (4, 6)
ORDER BY event_id;

Three expressions, three types

expressionresult for event 4type
payload -> 'price'"12.90", a quoted stringjsonb
payload ->> 'price'12.90, texttext
(payload ->> 'price')::numeric12.90, a numbernumeric

Use jsonb while you are still navigating through the document or comparing JSON values. text works well for displaying values and comparing them with strings. If you need to add prices, average them, or sort them by numeric value, use a numeric type.

Comparison: jsonb is compared with jsonb

The commandant asks: how many views did products priced at $12.90 get? There are two such products in the catalog, the book “SQL for Pros” and “Plush Cat Toy.”

It’s tempting to write payload -> 'price' = '12.90'. The query runs without an error, which makes the mistake easy to miss. The left side is jsonb, so PostgreSQL also parses the on the right as jsonb. The text 12.90 without quotes becomes a number. Event 6, where the price is stored as the number 12.90, matches. Event 4, with the JSON string "12.90", does not: as you saw in the previous lesson, a string and a number with the same digits are different values in jsonb.

With the double arrow, PostgreSQL compares two text values. In both events, the left side becomes 12.90, and the right side is also 12.90, so both rows match.

Below are all the views of those two products, along with both checks. We already worked through event 6. Before you run the query, predict the result for events 4, 18, and 35: they came from the old app version 3.9.2. What values will appear in the two comparison columns?

SELECT event_id,
       (payload -> 'price')::text AS price,
       payload -> 'price' = '12.90' AS arrow_eq,
       payload ->> 'price' = '12.90' AS text_eq
FROM app_events
WHERE event_type = 'view'
  AND payload ->> 'product_id' IN ('6', '18')
ORDER BY event_id;
Check yourself
The commandant is looking for events from app version 5.0.0 and writes WHERE payload -> 'app' = '5.0.0'. What happens?

Chaining: a box inside a box

The buyer’s city in event 1 is not at the top level; it is inside the user object. Here, the arrows go one after another: payload -> 'user' ->> 'city'. The first extracts the user object; the second gets city from it and returns the city as text.

Read the expression from left to right as a route: document, key user, key city. Every intermediate arrow keeps the result as jsonb so you can continue navigating through it. If you write payload ->> 'user' ->> 'city', the first double arrow turns the object into text, and PostgreSQL responds with operator does not exist: text ->> unknown. You cannot continue a path through ordinary text.

Choose the final arrow based on what you plan to do with the value you find. For text in a report or a string comparison, use the double arrow. If the path through the document continues, keep using the single arrow.

Look at three views. For event 1, the path to the city gives Tampa, while payload -> 'user' ->> 'id' returns the buyer number, 23. Now consider events 6 and 8: what type will the buyer column have? In the document itself, the buyer number is stored as a number, but the final arrow is double.

SELECT event_id,
       payload -> 'user' ->> 'id' AS buyer,
       payload -> 'user' ->> 'city' AS city
FROM app_events
WHERE event_id IN (1, 6, 8)
ORDER BY event_id;

Now apply the same technique to payment gateway responses. The payment status is at the top level, the buyer’s email is inside customer, and the decline code is inside the error object. In the cell for payments 1, 2, and 9, only status is shown so far. Complete the two chains for the email and error_code columns, and before you run the query, decide what error_code will contain for payment 1, which succeeded without an error.

SELECT payment_id,
       response ->> 'status' AS status
FROM payments
WHERE payment_id IN (1, 2, 9)
ORDER BY payment_id;

Array element position

Array elements do not have keys, but they do have positions. If you put an integer to the right of a single arrow, it returns the element at that position: payload -> 'items' -> 0. Counting starts at zero, as in many programming languages: 0 is the first element, 1 is the second.

Take order 5003, event 7: its items array contains three books. Read payload -> 'items' -> 0 ->> 'name' step by step. The first arrow extracts the array. The second takes element 0, the object for the first item. The third extracts its name as text. The result is SQL for Pros.

You can also count from the other end. A negative position -1 means the last element, and -2 means the second-to-last. This saves you from having to find the array length first when you need the final item.

Going past the end of an array does not raise an error. The arrow simply returns NULL, just as it does for a missing key.

Before you run the query, fill in the four columns in your head. Which book is at position 2? What will position 3 return? And which title will you get with -1?

SELECT payload -> 'items' -> 0 ->> 'name' AS item_0,
       payload -> 'items' -> 2 ->> 'name' AS item_2,
       payload -> 'items' -> 3 ->> 'name' AS item_3,
       payload -> 'items' -> -1 ->> 'name' AS item_last
FROM app_events
WHERE event_id = 7;

Charge attempts in the gateway response are stored in the charges array. Usually there is only one attempt, but payment 4 has two: the first timed out, and the second succeeded. Payment 11 has an empty array because the payment is still being processed and there have been no charge attempts yet.

The cell already shows the status of the first attempt, first_try. Add last_try next to it for the status of the final attempt. Before you run the query, predict both columns for payments 3, 4, and 11.

SELECT payment_id,
       response -> 'charges' -> 0 ->> 'status' AS first_try
FROM payments
WHERE payment_id IN (3, 4, 11)
ORDER BY payment_id;

Also useful

You can shorten a long chain to a path: payload #>> '{user,city}' does the same thing as payload -> 'user' ->> 'city'. The #> operator returns jsonb, while #>> returns text. We’ll work with paths in detail in the next chapter.

To get an array’s length, use jsonb_array_length(payload -> 'items'). For order 5003, the function returns 3, while the length of charges for payment 11 is 0.

From text to a number

After the double arrow, the price is text. If you need to add it, divide it, or compare it by value, convert the text to a number: (payload ->> 'price')::numeric.

The parentheses are required here. The :: operator binds more tightly than the arrows, so PostgreSQL reads payload ->> 'price'::numeric very differently from what you intended: it first tries to turn the word 'price' into a number and fails with invalid input syntax for type numeric: "price".

Return to events 4 and 6. In the first, the price is stored as a string; in the second, as a JSON number. Before you run the query, decide whether the values in the price column will be the same after the cast and what type the final column will show.

SELECT event_id,
       payload ->> 'price' AS price_text,
       (payload ->> 'price')::numeric AS price,
       pg_typeof((payload ->> 'price')::numeric) AS price_type
FROM app_events
WHERE event_id IN (4, 6)
ORDER BY event_id;

Now consider money from the payment gateway. Amounts there are stored in cents: for payment 1, the value is 7970. To get dollars, cast the value to a number and divide by 100. round(…, 2) keeps two digits after the decimal point because dividing a numeric value without rounding would leave a long tail of zeros.

Before you run the query, calculate how many dollars you expect for payments 1, 2, and 4. The order number appears next to each one, so you can check the amount against the order data you already know.

SELECT payment_id, order_id,
       response ->> 'amount' AS cents,
       round((response ->> 'amount')::numeric / 100, 2) AS dollars
FROM payments
WHERE payment_id IN (1, 2, 4)
ORDER BY payment_id;

The cannot cast jsonb string to type numeric error

A common shortcut is to skip one step and cast the result of the single arrow directly to a number: (payload -> 'price')::numeric. This cast has been supported for jsonb since PostgreSQL 11. It works for event 6 because the value under the key is already a number.

In event 4, however, the value is a JSON string. You can cast jsonb directly to a number only when the value inside is already a JSON number. On a string, PostgreSQL stops with:

ERROR:  cannot cast jsonb string to type numeric

The error message describes the problem directly: the value inside is a string. PostgreSQL does not check whether its characters happen to look like a number. With the double arrow, the path is different: first you get ordinary text 12.90, and that text can then be cast to a number.

Try this in the query. The commandant needs the viewing history for “Plush Cat Toy,” product 18: date and numeric price. The query below fails on the first matching row. Fix it with one replacement.

Find and fix the bug
The query fails with cannot cast jsonb string to type numeric because the old app sent the price as a string. Change only how the price is extracted from the document. Do not touch the filter conditions, columns, or sorting: after the fix, there should still be three views, each with a numeric price.
SELECT event_id, created_at,
       (payload -> 'price')::numeric AS price
FROM app_events
WHERE event_type = 'view'
  AND payload ->> 'product_id' = '18'
ORDER BY event_id;

Sorting: why 9 is greater than 800

The commandant’s next report is about household appliances. Two product cards list their power: Coffee Maker at 800 W and Desk Lamp at 9 W. They need to be ordered from higher-powered to lower-powered.

Power is stored in attrs under the key power_w. The double arrow returns it as text, and PostgreSQL compares text character by character from left to right. For '800' and '9', it first compares 8 with 9. Nine is greater, so the comparison stops there; the remaining two characters in 800 never matter. That is why Desk Lamp unexpectedly appears above Coffee Maker.

The mistake is easy to spot with numbers of different lengths: as text, '10' is less than '9', and '1000' is less than '12'. If every value has the same length, such as $12.90 and $59.90, the query can look perfectly reasonable for quite a while. I would not put that sort order into a report without testing it on at least one short and one long number.

Which appliance will come first if you sort the text attrs ->> 'power_w' in descending order? Answer first, then run the query.

SELECT product_id, name, attrs ->> 'power_w' AS power_w
FROM product_cards
WHERE product_id IN (13, 16)
ORDER BY attrs ->> 'power_w' DESC;
For text, the first differing character decides; for a number, the numeric value does. That is why '9' is greater than '800' even though 9 is less than 800.

Before sorting, convert the text to a number: ORDER BY (attrs ->> 'power_w')::numeric DESC. Now PostgreSQL compares 800 and 9 as numbers, so Coffee Maker comes first.

The same mistake can happen in WHERE. The condition attrs ->> 'power_w' > '100' compares two strings. For Desk Lamp, it is true: the first character '9' is already greater than '1' from '100'.

Below are three checks for “above 100 W” on the same appliances. You can work out the single-arrow version, the as_jsonb column, in advance. attrs -> 'power_w' > '100' compares jsonb with jsonb; both values in the documents are numbers, so they are compared by numeric value. Coffee Maker gives true, Desk Lamp false. Try to fill in the other two columns yourself.

SELECT product_id, name,
       attrs ->> 'power_w' > '100' AS as_text,
       attrs -> 'power_w' > '100' AS as_jsonb,
       (attrs ->> 'power_w')::numeric > 100 AS as_number
FROM product_cards
WHERE product_id IN (13, 16)
ORDER BY product_id;

ordering looks at type first

jsonb has its own comparison and sorting rules. Type comes first: null is less than a string, a string is less than a number, a number is less than a boolean, followed by arrays and objects. Only values of the same type are compared in the familiar way: numbers by value, strings as text.

That means sorting with -> can look correct for a long time while every value has the same type. As soon as one price arrives as a string, it sorts before every number regardless of the digits inside it.

Check this with three : the number 9, the number 800, and the string "1000". The cell below sorts them as jsonb in ascending order. Where will the string containing one thousand end up?

SELECT doc
FROM (VALUES ('9'), ('800'), ('"1000"')) AS demo(doc)
ORDER BY doc::jsonb;

Now try it without a ready-made solution. Three products have a piece count: Cookware Set has 12 items, Building Blocks has 120, and 1000-Piece Puzzle has 1000. First, work out the ascending text order of those three values in your head. Run the cell and check yourself. Then fix the ORDER BY directly in the editor so the products are ordered by their actual number of pieces, and run the query again.

SELECT product_id, name, attrs ->> 'pieces' AS pieces
FROM product_cards
WHERE product_id IN (14, 17, 19)
ORDER BY attrs ->> 'pieces';

The final task in this lesson comes without a hint in the main text. The commandant is preparing a report on products in the Toys category: the minimum age for each one, from youngest to oldest. The query runs and even starts the list correctly, with Plush Cat Toy for the youngest children. Then the order breaks: 0, 12, 3, 8. Somehow, 1000-Piece Puzzle for twelve-year-olds appears second.

Find and fix the bug
The ages are not in numeric order because they are being sorted as text. Fix only the sorting. Do not change the columns, the filter, or how the age_from column is displayed. After the fix, the order should be 0, 3, 8, 12.
SELECT product_id, name, attrs ->> 'age_from' AS age_from
FROM product_cards
WHERE category = 'Toys'
ORDER BY attrs ->> 'age_from';
Practice: solve the tasks
Solved 0 of 2 · any 1 is enough to pass

Arrows in other databases

The -> and ->> operators also appear outside PostgreSQL. In MySQL since version 5.7, the same two arrows work, but the right side uses a path such as '$.price': -> returns , while ->> removes the quotes. SQLite since version 3.38 supports both arrows with either a key or a path. ClickHouse and BigQuery use functions for the same job; we’ll get to them in chapter six.

PostgreSQL 17 added the SQL/JSON standard functions JSON_VALUE and JSON_QUERY, so you may already see them in newer examples online. This course’s sandbox runs PostgreSQL 16, where those functions are not available yet. The arrow operators work in both PostgreSQL 16 and PostgreSQL 17.

Common mistakes

Comparing a single arrow with a number

Scenario: views of two products priced at $12.90.

Expectation: payload -> 'price' = '12.90' finds every view at that price.

What actually happens: the query finds only events where the price is stored as a number. PostgreSQL treats the string "12.90" and the JSON number 12.90 as different values, so three of the four views silently disappear from the result.

How to check: if you’re comparing with text, use ->>; for calculations, cast the result to a number. If you’re unsure about the type, display jsonb_typeof(payload -> 'price') next to the value.

Putting a double arrow in the middle of a chain

Scenario: event 1, payload ->> 'user' ->> 'city'.

Expectation: the buyer’s city.

What actually happens: you get operator does not exist: text ->> unknown. The first double arrow already turned the user object into text, and you cannot continue a JSON path from ordinary text.

How to check: while the path continues, use single arrows; use the double arrow only at the final step.

Forgetting parentheses around the arrow expression

Scenario: event 6.

Expectation: payload ->> 'price'::numeric returns the price as a number, and payload -> 'price' + 0.01 adds one cent to it.

What actually happens: both expressions fail. :: and + bind more tightly than the arrows, so PostgreSQL starts by operating on something other than the extracted result. The errors differ, invalid input syntax for type numeric: "price" and invalid input syntax for type integer: "price", but the cause is the same: the database tries to process the word 'price' itself.

How to check: if another operation comes after the arrow, put the extracted result in parentheses first: (payload ->> 'price')::numeric + 0.01.

Putting the array position in quotes

Scenario: order 5003, payload -> 'items' -> '0'.

Expectation: the first item in the order.

What actually happens: you get NULL. '0' in quotes is text, so PostgreSQL looks for an object key with that name. An array has no such key, so the database returns an empty value without an error.

How to check: write an element position as an integer without quotes: -> 0.

Sorting numbers as text

Scenario: Coffee Maker at 800 W and Desk Lamp at 9 W.

Expectation: ORDER BY attrs ->> 'power_w' DESC puts Coffee Maker first.

What actually happens: Desk Lamp comes first because in a text comparison, the first character 9 is greater than 8.

How to check: add numbers of different lengths to your test data. With four-digit prices the mistake can hide easily, but a $9.90 product exposes it right away.

Applying this to your own documents

Before choosing an arrow, answer two questions. What will I do next with the value I find? How is that value actually stored in the live ?

For text in a report or a comparison with a string, you usually want ->>. While you’re still navigating through the document, or when you genuinely need to compare JSON values, keep ->. For calculations, numeric sorting, and comparisons with numbers, extract text first and cast it: (… ->> 'key')::numeric. The same technique works for dates with ::date or ::timestamp.

You can check the actual type with jsonb_typeof. I would do this at least once on real data, even if the API documentation promises a number. In our parcels, the old app sent the price as the string "12.90", while the new app sent the number 12.90; the schema alone would not have revealed that difference.

For a quick check, keep two awkward examples handy: 9 next to 800, and "12.90" next to 12.90. The first pair catches text sorting of numbers with different lengths; the second catches a mix of JSON strings and JSON numbers. These examples usually make the mistake obvious.

Key takeaways
  • -> extracts a value by key or position and returns jsonb: a string keeps its -string quotes, while an object remains an object.
  • ->> returns text: the quotes disappear, so "12.90" and 12.90 look the same after extraction.
  • Navigate nested documents with a chain: payload -> 'user' ->> 'city'. While the path continues, use single arrows; put the double arrow last.
  • Write an element position as an integer without quotes. Counting starts at zero, -1 gets the last element, and going out of bounds returns NULL without an error.
  • For numeric comparison and sorting, cast text to a number: (attrs ->> 'power_w')::numeric. Otherwise, '9' sorts above '800'.
  • (payload -> 'price')::numeric fails on a JSON string with cannot cast jsonb string to type numeric. If you extract the value with ->> first, the resulting text can be cast to a number.

We’ve now pulled prices and cities out of documents into separate columns. Along the way, we encountered NULL several times: for a successful payment with no error object and when going past the end of an array. Buyer settings contain even more of these missing values, and the same NULL can represent different situations there.