Summary: in this tutorial, you will learn how to use the PostgreSQL jsonb_agg()
function to aggregate values into a JSON array.
Introduction to the PostgreSQL jsonb_agg() function
The jsonb_agg()
function is an aggregate function that allows you to aggregate values into a JSON array.
The jsonb_agg()
function can be particularly useful when you want to create a JSON array from data of multiple rows.
Here’s the syntax of the jsonb_agg()
function:
In this syntax:
expression
: is any valid expression that evaluates to a JSON value.
The jsonb_agg()
function returns a JSON array that consists of data from multiple rows.
PostgreSQL jsonb_agg() function example
Let’s explore some examples of using the jsonb_agg()
function.
First, create a new table called products
:
Second, insert some rows into the products
table:
Third, use the jsonb_agg()
function to aggregate product information into a JSON array:
Output:
First, create new tables called departments
and employees
:
Second, insert rows into departments
and employees
tables:
The departments
table:
The employees
table:
Third, use the jsonb_agg()
function to retrieve departments and a list of employees for each department in the form of a JSON array:
Output:
First, drop the departments and employees tables:
Second, recreate the departments and employees tables:
Third, insert rows into the departments and employees tables:
Output:
The departments
table:
The employees
table:
Third, use the jsonb_agg()
function to retrieve departments and a list of employees for each department in the form of a JSON array:
Output:
In this example, the IT department has no employees therefore jsonb_agg()
function returns an array that contains a null value.
To skip the null and make the JSON array an empty array, you can use the jsonb_agg_strict()
function:
Output:
The jsonb_agg_strict()
function works like the jsonb_agg()
except that it skips the null values.
- Use the
jsonb_agg()
function to aggregate values into a JSON array.