Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select distinct values by key from JSONB column

Tags:

sql

postgresql

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.

like image 356
ken4z Avatar asked Dec 19 '25 10:12

ken4z


1 Answers

here is one way:

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

db<>fiddle here

like image 69
eshirvana Avatar answered Dec 21 '25 04:12

eshirvana



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!