PostgreSQL jsonb_path_exists() Function
Summary: in this tutorial, you will learn how to use the PostgreSQL jsonb_path_exists()
function to check if a JSON path returns any item for a specified JSON document.
Introduction to the PostgreSQL jsonb_path_exists() function
The jsonb_path_exists()
function allows you to check if a JSON path matches any element in a JSON document.
Here’s the syntax of the jsonb_path_exists()
function:
In this syntax:
jsonb_data
is a JSON document where you want to check for a JSON path.json_path
is the path that you want to check.
The jsonb_path_exists()
function returns true if the json_path
returns any elements in the jsonb_data
document or false otherwise.
PostgreSQL jsonb_path_exists() function example
Let’s take some examples of using the jsonb_path_exists()
function.
Setting up a sample table
First, create a new table called products
that store product information:
The products
table has the attributes
column whose data type is JSONB
.
Second, insert rows into the products
table:
Output:
1) Basic jsonb_path_exists() function example
The following example uses the jsonb_path_exists()
function to check whether the CPU specification exists for any product:
Output:
2) Using the jsonb_path_exists() function in the WHERE clause
The following example uses the jsonb_path_exists()
function with the jsonb_path_query()
function to retrieve the CPU
specification of any products that have CPU
spec:
Output:
Summary
- Use the
jsonb_path_exists()
function to check the existence of JSON Path expressions within JSONB data