PostgreSQL jsonb_path_query_first() Function
Summary: in this tutorial, you will learn how to use the PostgreSQL jsonb_path_query_first()
function to extract the first JSON value that matches a JSON path expression from a JSON document.
Introduction to the PostgreSQL jsonb_path_query_first() function
The jsonb_path_query_first()
function allows you to query data from a JSONB document based on a JSON path expression and return the first match.
Here’s the basic syntax of the jsonb_path_query_first()
function:
In this syntax:
- First, specify a JSONB data from which you want to query data.
- Second, provide a JSON path to match elements in the JSONB data.
If the jsonb_path_query_first()
function doesn’t find any match, it returns NULL
.
PostgreSQL jsonb_path_query_first() function examples
Let’s explore some examples of using the jsonb_path_query_first()
function.
1) Basic jsonb_path_query_first() function example
The following example uses the jsonb_path_query_first()
function to get the first pet of a person:
Output:
2) Using the jsonb_path_query_first() function with table data
First, create a new table called person
:
In the person
table, the data
column has the type of JSONB that stores employee information including name, age, and pets.
Second, insert data into the person
table:
Third, retrieve the first pet name using the jsonb_path_query_first()
function:
Output:
3) Handling missing paths
The following example attempts to find an element whose path does not exist:
Output:
In this case, the person object doesn’t have an email
key, therefore the result is NULL
.
Summary
- Use the
jsonb_path_query_first()
function to extract the first JSON value that matches a JSON path expression from a JSON document.