patternsqlMinor
will a record set derived from jsonb_to_recordset always maintain the order of the items in a JSON array
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.
"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
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 ordinalityContext
StackExchange Database Administrators Q#197959, answer score: 6
Revisions (0)
No revisions yet.