JSON Extract Postgres Operators
Extract nested fields from JSONB columns using Postgres arrow and double arrow operators with path expressions.
Code
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
Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.CSV to JSON ConverterConvert comma-separated values into a JSON array of objects using the first row as field names, with support for quoted and escaped fields.
FAQ
- What relations does the SQL touch?
- `events` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.