PostgreSQL jsonb_object_agg() Function
Summary: in this tutorial, you will learn how to use the PostgreSQL jsonb_object_agg()
function to aggregate key/value pairs into a JSON object.
Introduction to the PostgreSQL jsonb_object_agg() function
The PostgreSQL jsonb_object_agg()
function is an aggregate function that allows you to collect key/value pairs into a JSON object.
The jsonb_object_agg()
can be useful when you want to aggregate data from multiple rows into a single JSON object or construct complex JSON output.
Here’s the syntax of the jsonb_object_agg()
function:
In this syntax:
key
represents the key for the JSON object. The key must not be null.value
represents the value for the corresponding key.
The jsonb_object_agg()
returns a JSON object that consists of key/value pairs.
PostgreSQL jsonb_object_agg() function examples
Let’s explore some examples of using the PostgreSQL jsonb_object_agg()
function.
1) Basic PostgreSQL jsonb_object_agg() function example
First, create a table called departments
:
Second, insert some rows into the departments
table:
Third, use the jsonb_object_agg()
function to create an object whose key is the department name and value is the id:
Output:
2) Using the jsonb_object_agg() function with GROUP BY clause
First, create a new table called employees
:
Second, insert some rows into the employees
table:
Output:
Third, use the jsonb_object_agg()
function to get the department name and a JSON object that contains employee details of the department including employee name and salary:
Output:
Note that we use the jsonb_pretty()
function to format JSON.
Alex Miller has not had a salary yet so his salary is null. The jsonb_object_agg()
also collects the null into the JSON object.
To skip nulls, you can use the jsonb_object_agg_strict()
function as follows:
Output:
The jsonb_object_agg_strict()
function works like the jsonb_object_agg()
function except that it skips null values.
Summary
- Use the
jsonb_object_agg()
function to aggregate key/value pairs into a JSON object. - Use the
jsonb_object_agg()
function to aggregate key/value pairs into a JSON object and skip null values.