PostgreSQL jsonb_path_query() Function
Summary: in this tutorial, you will learn how to use the PostgreSQL jsonb_path_query()
function to query JSONB
data using JSON path expressions.
Introduction to the PostgreSQL jsonb_path_query() function
The jsonb_path_query()
function allows you to query JSONB data based on a JSON path expression.
Here’s the basic syntax of the jsonb_path_query()
function:
In this syntax:
jsonb_data
is the JSONB data that you want to query.path_expression
is a JSON path expression that locates values or elements in the JSONB data.
The jsonb_path_query()
function returns JSONB data that matches the specified JSON path expression.
If the path_expression
does not locate any element in the jsonb_data
, the function returns NULL
.
PostgreSQL jsonb_path_query() function example
Let’s take some examples of using the jsonb_path_query()
function.
Setting up a sample table
First, create a table named products
with a JSONB column names attributes
to store product attributes:
Second, insert some rows into the products
table:
1) A basic jsonb_path_query() function example
The following example uses the jsonb_path_query()
function to retrieve the brand and price of all products:
Output:
2) More complex JSON path example
The following example uses the jsonb_path_query()
function to query nested attributes such as retrieving the CPU specification of laptops:
Output:
Summary
- Use the
jsonb_path_query()
function to query JSONB data based on JSON path expressions.