1

I have a postgresql data with values (it is jsonb type column):

SELECT data FROM orders;

   [
    {
        "food_id": "1",
        "table": "A12",
    },
    {
        "food_id": "2",
        "table": "A14",
    }
   ]

I can easily SELECT by providing data as it is, but how to convert it into simplified ?

My expected result:

SELECT ??? as food_tables FROM orders;

["A12", "A14"]

I personally still did not understand how jsonb_array_elements() works.

Thanks!

4
  • "I have a postgresql data with values" - multiple values (rows)? Or just one? Commented Jun 8, 2021 at 0:34
  • "I personally still did not understand how jsonb_array_elements() works." - it seems you already know the right approach. Can you be more specific about what you didn't understand, and show us how you tried to use it? Commented Jun 8, 2021 at 0:36
  • @Bergi multiple. I just dont know how to write syntax for the SELECT Commented Jun 8, 2021 at 2:45
  • Which Postgres version are you using? Commented Jun 8, 2021 at 5:16

2 Answers 2

1

If you are using Postgres 12 or later, you can use jsonb_path_query_array()

select jsonb_path_query_array(data, '$[*].table') as food_tables
from orders
Sign up to request clarification or add additional context in comments.

2 Comments

Sorry I did not specify my PostgreSQL version. Mine is using 9.6
@mokalovesoulmate: then you will need to use Laurenz's answer
0

You could perform a lateral cross join with the unnested array elements and extract the attributes:

SELECT jsonb_agg(d.elem -> 'table')
FROM orders
   CROSS JOIN LATERAL jsonb_array_elements(orders.data) AS d(elem)
GROUP BY orders.id;

Use array_agg instead of jsonb_agg if you want a PostgreSQL array.

It is a mistake to model tabular data as a JSON array. Change your data model so that each array element becomes a row in a database table.

4 Comments

Hi Laurenz, thanks for the answer. I cannot update the current data model since it is an existing old app. I tried your query but that is not what I needed. I needed the A12 and A14 in the same row. I've updated the question into "expected result".
Hi Laurenz, I see you updated your answer. Its almost correct! Unfortunately it also merges all other rows from same table into single row. @a_horse_with_no_name answer is the one.
You didn't specify what you want.
Thank you and sorry @Laurenz! I was okay to upgrade to pg12 but after seeing your updated answer, I can stay with pg9.6. Also great help with @a_horse_with_no_name.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.