Skip to content
Advertisement

Select Unique value from a JSON Array – PostgreSQL JSON column

I have the following JSON document stored in a PostgreSQL JSON column:

I am trying to retrieve the price for specific customer_ID I am using this query to get the price for Customer_ID=1

The problem is that i am getting the same results for Customer_ID=1 and for Customer_ID=10 I am basically getting both elements of the array instead of just one. I don’t know what i am doing wrong

Advertisement

Answer

You can use a lateral join to unnest the array elements, and then filter on the customer with a where clause; this leaves you with just one row, from which you can extract the price:

Note that you don’t need to cast the customer id to an int, as it is already stored in the proper format in the json array.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement