PostgreSQL jsonb_populate_recordset() Function
Summary: in this tutorial, you will learn how to use the PostgreSQL jsonb_popuplate_recordset()
function to populate the fields of a record type from a JSON array of objects.
Introduction to the PostgreSQL jsonb_popuplate_recordset() function
The jsonb_populate_recordset()
function allows you to populate the fields of a record type from a JSON array of objects.
In other words, the jsonb_popuplate_recordset()
function converts a JSON array of objects with the JSONB type into a set of records of a specified type.
Here’s the syntax of the jsonb_populate_recordset()
function:
In this syntax:
target
represents the target record type to which the JSONB data will be mapped.json_object
is a JSON array of objects from which the records will be populated. The jsonb_array has the type of JSONB.
The jsonb_populate_recordset()
function returns a set of records of a specified type, with each record’s fields populated using the corresponding key-value pairs from the JSONB objects in the array.
PostgreSQL jsonb_popuplate_recordset() function examples
Let’s explore some examples of using the jsonb_populate_recordset()
function.
1) Basic jsonb_populate_recordset() function example
First, create a new type called address
:
Second, use the jsonb_populate_recordset()
function to populate the address custom type from a JSON array of objects:
Output:
2) Using the jsonb_populate_recordset() function with table data
First, create a new table called employees
:
Second, insert some rows into the employees
table:
Third, use jsonb_populate_recordset()
to query the data from the employees
table in a structured format:
Output:
Summary
- Use the
jsonb_popuplate_recordset()
function to populate the fields of a record type or a custom composite type from a JSON object.