PostgreSQL jsonb_array_elements Function

My first PostgreSQL jsonb_array_elements query lost two of five orders: the empty and NULL arrays. The job itself is simple. jsonb_array_elements('["Ohio","Texas"]') returns one jsonb row per element.

The fix is LEFT JOIN LATERAL ... ON true. Also, the plain version returns "Ohio" with quotes; the _text version returns Ohio.

Six examples follow, from a bare call to joins, filters and the object error. Tested on PostgreSQL 18.6 for Windows, with psql in VS Code.

PostgreSQL jsonb_array_elements Function Syntax

Here is the syntax:

jsonb_array_elements ( jsonb ) → setof jsonb
jsonb_array_elements_text ( jsonb ) → setof text
json_array_elements ( json ) → setof json
json_array_elements_text ( json ) → setof text

The argument is a JSON array; only its top level expands. Match the pair to your column, as my PostgreSQL JSON vs JSONB comparison explains.

Return value: rows in a column named value. NULL input returns zero rows.

Availability: the json pair since PostgreSQL 9.3, the jsonb pair since 9.4.

When to Use the jsonb_array_elements Function in PostgreSQL

Use jsonb_array_elements when you need to:

  • turn API line items into report rows
  • sum values stored inside a JSON array
  • find rows where any element matches
  • sort by a value inside JSON, as in ORDER BY on a JSON field

Run this once. Every example uses these five US orders:

DROP TABLE IF EXISTS orders;
CREATE TABLE orders (
  id       int PRIMARY KEY,
  customer text,
  items    jsonb
);
INSERT INTO orders VALUES
 (1001, 'Hannah Brooks',
  '[{"sku":"MUG-12","qty":2,"price":14.50},
    {"sku":"TEE-M","qty":1,"price":22.00}]'),
 (1002, 'Tyler Reed',     '[{"sku":"CAP-01","qty":3,"price":18.00}]'),
 (1003, 'Grace Miller',   '[]'),
 (1004, 'Marcus Bennett', NULL),
 (1005, 'Olivia Carter',  '[{"sku":"MUG-12","qty":4,"price":14.50}]');

Example 1: jsonb_array_elements vs jsonb_array_elements_text

Let’s start small. I want both versions side by side:

SELECT *
FROM ROWS FROM (
  jsonb_array_elements('["Ohio", "Texas"]'),
  jsonb_array_elements_text('["Ohio", "Texas"]')
) AS t(as_jsonb, as_text);

Output:

 as_jsonb | as_text 
----------+---------
 "Ohio"   | Ohio
 "Texas"  | Texas
(2 rows)

For Ohio, this returns "Ohio" (jsonb) and Ohio (text). Compare plain strings with _text.

Example 2: Expand a JSON Array to Rows in PostgreSQL (LATERAL Join)

Each order has an items array. The goal is one row per item:

SELECT o.id, i->>'sku' AS sku,
       (i->>'qty')::int AS qty
FROM orders o
CROSS JOIN LATERAL jsonb_array_elements(o.items) AS i
ORDER BY o.id;

Output:

  id  |  sku   | qty 
------+--------+-----
 1001 | MUG-12 |   2
 1001 | TEE-M  |   1
 1002 | CAP-01 |   3
 1005 | MUG-12 |   4
(4 rows)
PostgreSQL CROSS JOIN LATERAL jsonb_array_elements returning 4 item rows for orders 1001, 1002 and 1005
Orders 1003 and 1004 are missing.

That returns 4 rows. ->> returns text, so cast qty before math. More on join types in my PostgreSQL joins tutorial.

Example 3: Keep Rows with Empty or NULL Arrays (LEFT JOIN LATERAL)

Say you need orders 1002 to 1004, even Grace’s empty array:

\pset null '(null)'

SELECT o.id, i->>'sku' AS sku
FROM orders o
LEFT JOIN LATERAL jsonb_array_elements(o.items) AS i
  ON true
WHERE o.id BETWEEN 1002 AND 1004
ORDER BY o.id;

Output:

  id  |  sku   
------+--------
 1002 | CAP-01
 1003 | (null)
 1004 | (null)
(3 rows)
PostgreSQL LEFT JOIN LATERAL jsonb_array_elements ON true returning orders 1003 and 1004 with null sku
LEFT JOIN LATERAL keeps the empty and NULL arrays.

That returns 3 rows, with (null) for 1003 and 1004. Drop the WHERE, run the SELECT again, and you should see 6 rows. Swap NULL for a label with COALESCE.

Example 4: Get Each Element’s Position WITH ORDINALITY

Next, I want each item’s position in Hannah’s array:

SELECT x.n, x.item->>'sku' AS sku
FROM orders o,
     jsonb_array_elements(o.items) WITH ORDINALITY AS x(item, n)
WHERE o.id = 1001;

Output:

 n |  sku   
---+--------
 1 | MUG-12
 2 | TEE-M
(2 rows)

MUG-12 is item 1 and TEE-M is item 2. To number by a sort instead, use ROW_NUMBER.

Example 5: Filter PostgreSQL Rows by an Array Element

I want to flag orders with an item of qty 3+, and orders holding MUG-12:

\pset footer off
SELECT id,
  EXISTS (SELECT 1 FROM jsonb_array_elements(items) AS i
          WHERE (i->>'qty')::int >= 3) AS qty_3_plus,
  items @> '[{"sku": "MUG-12"}]' AS has_mug
FROM orders
WHERE items IS NOT NULL
ORDER BY id;

Output:

  id  | qty_3_plus | has_mug 
------+------------+---------
 1001 | f          | t
 1002 | t          | f
 1003 | f          | f
 1005 | t          | t
PostgreSQL EXISTS with jsonb_array_elements true for orders 1002 and 1005, @> containment true for 1001 and 1005
EXISTS handles ranges; @> handles equality.

qty_3_plus is true for 1002 and 1005; has_mug is true for 1001 and 1005. @> only tests equality, so ranges need an EXISTS subquery.

Example 6: Fix “cannot extract elements from an object” in PostgreSQL

Order 1006 stores an object. The goal is a query that skips it:

\set ON_ERROR_STOP off

INSERT INTO orders VALUES
 (1006, 'Ava Turner', '{"sku":"CAP-01","qty":1}');

SELECT o.id, i->>'sku' AS sku
FROM orders o, jsonb_array_elements(o.items) AS i;

SELECT count(*)
FROM orders o, jsonb_array_elements(o.items) AS i
WHERE jsonb_typeof(o.items) = 'array';

Output:

psql:jsonb-array-elements-object-error.sql:7: ERROR:  cannot extract elements from an object
 count 
-------
     4
(1 row)
PostgreSQL jsonb_array_elements error cannot extract elements from an object, then jsonb_typeof guard returning count 4
The jsonb_typeof guard skips order 1006.

The plain query fails; the guarded one counts 4 rows. A string fails too, with cannot extract elements from a scalar.

jsonb_array_elements vs jsonb_path_query vs unnest: Which Should You Use?

Featurejsonb_array_elementsjsonb_path_queryunnest
Inputjsonb arrayjsonb + pathSQL array
Object inputErrorReturns the objectn/a

My rule of thumb: jsonb_array_elements for rows, jsonb_path_query for one field ('$[*].sku'), PostgreSQL UNNEST for array columns.

Tips & Common Mistakes

  • Comma and CROSS joins drop empty or NULL arrays.
  • Objects fail with ERROR: cannot extract elements from an object.
  • Rebuild an array with jsonb_agg(value).
  • A GIN index serves @>, not the function. See PostgreSQL CREATE INDEX.

Wrapping Up

The PostgreSQL jsonb_array_elements function plus LEFT JOIN LATERAL covers most JSON-array reports. Copy Example 3 for reports. In MongoDB, $unwind does this job.

Next step: browse the complete list of PostgreSQL functions or the PostgreSQL 18 JSON functions docs.

Working with arrays in other ways? Start here:

Frequently Asked Questions

What is the difference between json_array_elements and jsonb_array_elements?

json_array_elements keeps each element’s original text. The jsonb version returns normalized jsonb.

How do I expand a nested JSON array in PostgreSQL?

Add a second LATERAL call on the inner array, like jsonb_array_elements(e->’tags’).

Is jsonb_array_elements slow on big tables?

It gets no index help. Filter with an indexed @> first, then expand.