Skip to content
Advertisement

Select distinct values by key from JSONB column

Postgres v12.0

I have a table

data
{“a”: “1”, “b”: “1”}
{“a”: “2”, “b”: “1”}

And I’d like to retrieve a distinct list of keys and the set of values for each key

key values
a [ “1”, “2” ]
b [ “1” ]

Not sure how to formulate a query to achieve those results.

Advertisement

Answer

here is one way:

select key , array_agg(distinct value) 
from table
join lateral (select * from json_each_text(datacolumn)) j on true 
group by key 

db<>fiddle here

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