JSON Extract Postgres Operators

Extract nested fields from JSONB columns using Postgres arrow and double arrow operators with path expressions.

SqlData Fetching

Code

sqlsnippet
10 lines
SELECT
  id,
  payload ->> 'name' AS name,
  payload -> 'address' ->> 'city' AS city,
  payload -> 'tags' -> 0 AS first_tag,
  jsonb_array_length(payload -> 'tags') AS tag_count
FROM events
WHERE payload @> '{"type": "order"}'
  AND (payload ->> 'name') IS NOT NULL
ORDER BY id;

Inside the snippet

At its core this is a single SELECT statement against events.

Breaking the statements into their working parts: a WHERE clause narrowing which rows one statement affects; an ORDER BY that fixes the output order; NOT NULL qualifiers on the required columns.

Putting it to use

The events table is the working surface here.

Core lines

SELECT
  id,
  payload ->> 'name' AS name,
  payload -> 'address' ->> 'city' AS city,
  payload -> 'tags' -> 0 AS first_tag,
  jsonb_array_length(payload -> 'tags') AS tag_count
FROM events
WHERE payload @> '{"type": "order"}'
  AND (payload ->> 'name') IS NOT NULL
ORDER BY id;

Interactive Tools for This Topic

FAQ

What relations does the SQL touch?
`events` — referenced directly, no join needed.