PostgreSQL jsonb_strip_nulls() Function
Summary: in this tutorial, you will learn how to use the PostgreSQL jsonb_strip_nulls()
function to recursively delete all object fields that have null values.
Introduction to the PostgreSQL jsonb_strip_nulls() function
The jsonb_strip_nulls()
function accepts a JSON document with the JSONB type and recursively deletes all object fields that have null values. It does not delete non-object fields with null values.
Here’s the syntax of the jsonb_strip_nulls()
function:
In this syntax, you specify a JSON document in which you want to delete all object fields with null values. The jsonb_data
must have the type JSONB
.
The jsonb_strip_nulls
returns a new jsonb_data
whose object fields with null values are removed.
If the jsonb_data
is null, the function returns NULL
.
PostgreSQL jsonb_strip_nulls() function example
Let’s take some examples of using the jsonb_strip_nulls()
function.
1) Basic jsonb_strip_nulls() function example
The following example uses the jsonb_strip_nulls()
function to remove object fields with null values:
Output:
In this example, the object field middle_name
has a null value therefore the jsonb_strip_nulls()
function removes it. The scores
array also has null but it is a non-object field, therefore, the jsonb_strip_nulls()
function does not delete it.
2) Using the jsonb_strip_nulls() function to recursively delete object fields with null values
First, create a new table called products
:
Second, insert data into the products
table:
Output:
Third, use the jsonb_strip_nulls()
function to remove all fields with null values recursively from the specs object and its nested object:
Output:
The output indicates that the ram
field and the entire extras
object, as well as its nested fields with null values, have been removed from the JSONB data.
Summary
- Use the
jsonb_strip_nulls()
function to recursively delete all object fields that have null values.