SQL json_array_elements function
FROM jsonb_array_elements(items) gives one row per array element. It is UNNEST for JSON arrays, and jsonb_array_elements_text returns the elements as text.
- Category
- Strings
- Returns
setof json or jsonb- In this category
- 162 of 172
Syntax
json_array_elements(json)
jsonb_array_elements(jsonb)
Each block is a separate form. The support table and the examples show which engine takes which.
Engine support
| Engine | Support | Notes |
|---|---|---|
| SQL Server | Not built in | OPENJSON covers it |
| PostgreSQL | Yes | both json and jsonb variants |
| MySQL | Not built in | JSON_TABLE covers it |
| SQLite | Different name or syntax | json_each covers it |
| Oracle | Not built in | No built-in equivalent. |
Examples
PostgreSQL
SELECT je.value FROM orders o, jsonb_array_elements(o.items) je;
PostgreSQL
SELECT je.value->>'sku' AS sku,
(je.value->>'qty')::int AS qty
FROM orders o, jsonb_array_elements(o.items) je;
Good to know
- Elements come back as JSON, so strings keep their quotes: '["a"]' yields "a". Use jsonb_array_elements_text when you want plain text values.
- Calling it on something that is not an array raises 'cannot extract elements from an object' (or from a scalar). Guard with jsonb_typeof(x) = 'array' when documents vary.
- Correlated per-row arrays are the common shape: FROM orders o, jsonb_array_elements(o.items) je; each order's items join back to the order.
Questions about json_array_elements
How do I join parent rows to array elements?
Comma or LATERAL join from the parent table: FROM orders o, jsonb_array_elements(o.items) je. Every parent row multiplies by its array length, including zero, which drops empty arrays from the result.
Where is the element index?
There is none on this function: use jsonb_array_elements WITH ORDINALITY AS je(value, pos) to add positions, the same pattern as unnest.
Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.
Related on SQLly
Cheat sheets for the engines that have it: PostgreSQL, SQLite.
Functions your engine actually has
SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.