// strings reference

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.

Catégorie
Strings
Returns
setof json or jsonb
In this category
162 of 172

Syntaxe

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.

Prise en charge des moteurs

MoteurSupportNotes
SQL Server Not built in OPENJSON covers it
PostgreSQL Oui 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.

Exemples

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;

Bon à savoir

  • 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.

Cheat sheets for the engines that have it: PostgreSQL, SQLite.

// fewer lookups

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.