PostgreSQL jsonb_array_elements() Function
Summary: in this tutorial, you will learn how to use the PostgreSQL jsonb_array_elements()
function to expand the top-level JSON array into a set of JSON values.
Introduction to the PostgreSQL jsonb_array_elements() function
The jsonb_array_elements()
function allows you to expand the top-level JSON array into a set of JSON values.
Here’s the basic syntax of the jsonb_array_elements()
function:
In this syntax, you specify a JSON array with a JSONB type that you want to expand its elements.
The jsonb_array_elements()
function will expand the elements of the json_array
into individual elements.
If you pass a non-array to the function, it’ll issue an error. If the json_array
is NULL
, the function returns an empty result set.
PostgreSQL jsonb_array_elements() function examples
Let’s explore some examples of using the jsonb_array_elements()
function.
1) Basic PostgreSQL jsonb_array_elements() function examples
The following example uses the jsonb_array_elements()
function to expand elements of a JSON array:
Output:
Note that the numbers 1, 2, 3 are the JSON values.
The following example uses the jsonb_array_elements()
function to expand an array of strings:
Output:
2) Using the jsonb_array_elements() function with nested arrays example
The following example uses the jsonb_array_elements()
function to expand elements of an array that contains another array:
Output:
3) Using the jsonb_array_elements() function with table data
First, create a table called employees
:
The skills
column has the JSONB type, which stores the skills of employees.
Second, insert some rows into the employees
table:
Third, retrieve all skills of employees:
Output:
It returns 12 skills.
It’s possible to use the DISTINCT
to get unique skills of all employees:
Output:
Summary
- Use the
jsonb_array_elements()
function to expand elements of the top-level JSON array.