HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlMinor

will a record set derived from jsonb_to_recordset always maintain the order of the items in a JSON array

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
theorderarrayalwaysderivedmaintainjsonb_to_recordsetrecordwillitems

Problem

I want to be able to retrieve a jsonb array of objects as a record set. Maintaining the order of objects is critical. Will jsonb_to_recordset always return the record set in the order of the array of objects?

Solution

Here's another solution using another of Postgres' json functions: jsonb_array_elements.

SELECT id, (value->>'benefit')::varchar as benefit, ordinality as rank
  FROM products 
  CROSS JOIN LATERAL jsonb_array_elements(benefits) with ordinality


"with ordinality" gives you the order of each array item and allows you to do an explicit order by on that field to ensure the order remains the same.

This stackoverflow post was very helpful

Code Snippets

SELECT id, (value->>'benefit')::varchar as benefit, ordinality as rank
  FROM products 
  CROSS JOIN LATERAL jsonb_array_elements(benefits) with ordinality

Context

StackExchange Database Administrators Q#197959, answer score: 6

Revisions (0)

No revisions yet.