Today I Learned

hashrocket A Hashrocket project

Build rows from jsonb data in PostgreSQL

PostgreSQL has a function called jsonb_to_recordset that will return your jsonb data as if it were rows in the database.

Say we have the following example table:

create table notes (title varchar, bullets jsonb);

insert into notes (title, bullets)
values ('Inspection', '[{"field": "Tires", "measured": "Tread Height", "value": "3mm"},{"field": "Brakes", "measured": "Caliper Boot", "value": "cracked"}]');

To use the jsonb_to_recordset function, we can do the following:

select title, field, measured, value
from notes
cross join lateral jsonb_to_recordset(notes.bullets) 
as temp(field varchar, measured varchar, value varchar);

The function gives us the following output:

   title    | field  |   measured   |  value  
------------+--------+--------------+---------
 Inspection | Tires  | Tread Height | 3mm
 Inspection | Brakes | Caliper Boot | cracked
See More #sql TILs
Looking for help? Hashrocket developers believe that data quality is as important as code quality. We enjoy all the challenges of relational databases, from finding the fastest index, to structuring data to fit the needs of an application. We're eager to share our experiences; check out PG Casts, our series of free PostgreSQL screencasts.