Skip to main content
Documents
Basic SyntaxMath FunctionsDate FunctionsJSON FunctionsDatabasesTables & Schema ManagementString FunctionsTriggersIndexes

PostgreSQL jsonb_array_elements()

PostgreSQL `jsonb_array_elements()` is a JSON function used to expand a JSON array into a set of JSON elements. It is particularly useful for querying and manipulating JSON data stored in PostgreSQL databases.

Usage

The `jsonb_array_elements()` function is employed when you need to process each element of a JSON array individually. It is commonly used in conjunction with `LATERAL` joins to iterate over array elements.

SELECT jsonb_array_elements(jsonb_column)
FROM table_name;

In this syntax, `jsonb_array_elements(jsonb_column)` deconstructs the JSON array in `jsonb_column` and returns each element as a separate row. Note that if the array is empty, no rows are returned, and if the input JSON is `null`, the result is also `null`.

Examples

1. Basic Usage

SELECT jsonb_array_elements('[1, 2, 3, 4]');

This example outputs each number in the JSON array `[1, 2, 3, 4]` as a separate row, resulting in four rows.

2. Extracting Elements from a Table Column

SELECT jsonb_array_elements(data)
FROM orders;

Assuming `data` is a column in the `orders` table containing JSON arrays, this query extracts and outputs each element of the arrays stored in the `data` column. Be cautious with non-array JSON objects, as these can lead to runtime errors.

3. Using with LATERAL Join

SELECT o.id, elem
FROM orders AS o, LATERAL jsonb_array_elements(o.items) AS elem;

In this example, each element of the `items` JSON array in the `orders` table is extracted and joined with the `orders` table to produce a row for each element, alongside the order's `id`. The `LATERAL` keyword allows each row from the orders table to be processed individually with its corresponding JSON array.

Tips and Best Practices

  • Ensure JSON validity. Always validate JSON data before using `jsonb_array_elements()` to avoid runtime errors.
  • Use LATERAL for joins. `LATERAL` allows each row to be processed with its specific JSON array, enabling complex joins.
  • Filter results early. Apply filters before expanding arrays to improve performance when working with large datasets.
  • Index JSONB columns. Consider indexing JSONB columns to accelerate queries involving JSON functions, especially when frequently querying large datasets.
  • Performance considerations. Be mindful of performance impacts when using `jsonb_array_elements()` on large or deeply nested JSON arrays.
  • Comparison with `json_array_elements()`. `jsonb_array_elements()` is used with JSONB data, which is stored in a decomposed binary format, offering improved performance over `json_array_elements()` in many cases.