JSON Data Query and Manipulation
Queries and manipulates JSON/JSONB data using operators for extraction, filtering, and modification of nested JSON structures in PostgreSQL.
Code
SELECT
id,
metadata->>'name' AS name,
metadata->'address'->>'city' AS city,
metadata->'tags' AS tags_array,
metadata #>> '{address,zip}' AS zip_code,
jsonb_array_length(metadata->'tags') AS tag_count
FROM documents
WHERE metadata @> '{"status": "published"}'
AND metadata->'address'->>'city' = 'New York'
AND metadata->'tags' ? 'featured'
AND metadata->>'priority' IS NOT NULL
ORDER BY (metadata->>'priority')::int DESC;
-- Update JSON data
UPDATE documents
SET metadata = jsonb_set(
metadata,
'{last_updated}',
to_jsonb(CURRENT_TIMESTAMP)
) || jsonb_build_object(
'view_count',
COALESCE((metadata->>'view_count')::int, 0) + 1
)
WHERE id = 42;
-- Extract and expand JSON array
SELECT
d.id,
tag.value AS tag
FROM documents d,
jsonb_array_elements(d.metadata->'tags') AS tag
WHERE d.metadata->'tags' IS NOT NULL;How the snippet works
What runs here is SELECT / UPDATE — documents are the objects involved.
What the statements actually assemble: a WHERE clause limiting the rows one statement is allowed to reach; an ORDER BY that fixes the output order; NOT NULL qualifiers on the required columns.
Applying it
The documents table is the working surface here.
Statements that matter
UPDATE documents
SET metadata = jsonb_set(
metadata,
'{last_updated}',
to_jsonb(CURRENT_TIMESTAMP)
) || jsonb_build_object(
'view_count',
COALESCE((metadata->>'view_count')::int, 0) + 1
)
WHERE id = 42;
SELECT
d.id,
tag.value AS tag
FROM documents d,
jsonb_array_elements(d.metadata->'tags') AS tag
WHERE d.metadata->'tags' IS NOT NULL;
Interactive Tools for This Topic
JSONPath TesterTest JSONPath expressions against JSON documents with dot notation, brackets, wildcards, and recursive descent.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.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.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.
FAQ
- Name the tables involved in this file.
- The references are `documents`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.