jsonb_array_elements_text Unnests JSON Arrays
Expand a JSONB array back into rows with jsonb_array_elements_text, keep each element's position with WITH ORDINALITY, then re-aggregate with jsonb_agg.
Code
-- JSONB 数组还原成行:每个元素一行,WITH ORDINALITY 保留原始位次
SELECT
doc_id,
tag,
ord - 1 AS tag_index -- ordinality 从 1 起,转成 0 基下标
FROM docs,
LATERAL jsonb_array_elements_text(doc->'tags') WITH ORDINALITY AS t(tag, ord)
ORDER BY doc_id, ord;
-- 反向聚合:jsonb_agg 把行重新收成 JSONB 数组
SELECT
doc_id,
jsonb_agg(tag ORDER BY ord) AS tags_restored
FROM docs,
LATERAL jsonb_array_elements_text(doc->'tags') WITH ORDINALITY AS t(tag, ord)
GROUP BY doc_id;
-- 展开后就能按元素筛选:找带某标签的文档
SELECT doc_id FROM docs, LATERAL jsonb_array_elements_text(doc->'tags') AS t(tag)
WHERE tag = 'urgent';How it works
SELECT statements share the script, touching docs.
Breaking the statements into their working parts: a WHERE clause constraining which rows the statement operates on; a GROUP BY that collapses matching rows into one output row per group; an ORDER BY that fixes the output order.
Applying it
Run the statement against the docs table.
Statements that matter
SELECT
doc_id,
jsonb_agg(tag ORDER BY ord) AS tags_restored
FROM docs,
LATERAL jsonb_array_elements_text(doc->'tags') WITH ORDINALITY AS t(tag, ord)
GROUP BY doc_id;
SELECT
doc_id,
tag,
ord - 1 AS tag_index -- ordinality 从 1 起,转成 0 基下标
FROM docs,
LATERAL jsonb_array_elements_text(doc->'tags') WITH ORDINALITY AS t(tag, ord)
ORDER BY doc_id, ord;
SELECT doc_id FROM docs, LATERAL jsonb_array_elements_text(doc->'tags') AS t(tag)
WHERE tag = 'urgent';
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.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.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 are the relations in play here?
- `docs`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.