Skip to content
Advertisement

PostgreSQL select specific items from JSONB array

I have a table like this:

I want to generate an output like this

As you can see I pull out the UPC from the array (targeting the first element in the array only).

Note that products if of type jsonb

I tried this:

But it gives a syntax error, I’m not sure exactly how to do array traversal in PostgreSQL

Also there is the possibility that products may be an empty array []

Advertisement

Answer

demo:db<>fiddle

  1. products -> 0 -> 'upc' gets the upc value of the first array element
  2. jsonb_build_object() builds one JSON object per record containing the order_number and upc value
  3. jsonb_agg() aggregates these JSON objects into one JSON array
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement