Postgres jsonb_each() function
Expands JSONB into a record per key-value pair
The jsonb_each
function in Postgres is used to expand a JSONB
object into a set of key-value pairs.
It is useful when you need to iterate over a JSONB
object's keys and values, such as when you're working with dynamic JSONB
structures where the schema is not fixed. Another important use case is performing data transformations and analytics.
Function signature
The function returns a set of rows, each containing a key and the corresponding value for each field in the input JSONB
object. The key is of type text
, while the value is of type JSONB
.
Example usage
Consider a JSONB
object representing a user's profile information. The JSONB
data will have multiple attributes and might look like this:
We can go over all the fields in the profile JSONB
object using jsonb_each
, and produce a row for each key-value pair.
This query returns the following results:
Advanced examples
jsonb_each
Assign custom names to columns output by You can use AS
to specify custom column names for the key and value columns.
This query returns the following results:
jsonb_each
output as a table or row source
Use Since jsonb_each
returns a set of rows, you can use it as a table source in a FROM
clause. This lets us join the expanded JSONB
data in the output with other tables.
Here, we're joining each row in the user_data
table with the output of jsonb_each
:
This query returns the following results:
Additional considerations
Performance implications
When working with large JSONB
objects, jsonb_each
may lead to performance overhead, as it expands each key-value pair into a separate row.
Alternative functions
jsonb_each_text
- Similar functionality tojsonb_each
but returns the value as a text type instead ofJSONB
.jsonb_object_keys
- It returns only the set of keys in theJSONB
object, without the values.- json_each - It provides the same functionality as
jsonb_each
, but acceptsJSON
input instead ofJSONB
.