PostgreSQL jsonb_path_query_array() Function
Summary: in this tutorial, you will learn how to use the PostgreSQL jsonb_path_query_array()
function to query JSONB data using a JSON path and return matched elements as a JSON array.
Introduction to PostgreSQL jsonb_path_query_array() function
The jsonb_path_query_array()
function allows you to query JSONB data using a JSON path expression.
Here’s the basic syntax of the jsonb_path_query_array()
function:
In this syntax:
- First, specify the
jsonb_data
that you want to query. - Second, provide a
json_path
that you want to match elements within thejsonb_data
.
The jsonb_path_query_array()
function returns the matched elements as a JSON array.
If the function does not find any matched element, it returns an empty array.
If either argument is NULL
, the function returns NULL
.
PostgreSQL jsonb_path_query_array() function example
Let’s explore some examples of using the jsonb_path_query_array()
function
1) Basic PostgreSQL jsonb_path_query_array() function example
The following example uses the jsonb_path_query_array()
function to get the employee names as an array:
Output:
In this example, the JSON path expression $.employees[*].name
locates the value of the name
key of all elements in the employees
array.
2) Using jsonb_path_query_array() function with table data
First, create a new table called employees
:
In the employees
table, the data
column has the type of JSONB
.
Second, insert some rows into the employees
table:
Output:
Third, use the jsonb_path_query_array()
function to retrieve the pet names of employees as a JSON array:
Output:
3) Handling missing paths
If the specified path doesn’t exist in the JSONB
data, the jsonb_path_query_array()
function returns an empty array. For example:
Output:
In this example, the employee object doesn’t have an address
key, so the result is an empty array.
Summary
- Use the
jsonb_path_query_array()
function to query JSONB data using a JSON path and return matched elements as a JSON array.