Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select Distinct Array Values from Postgresql Table

I have a PostgreSQL database table which looks like this

content
title          category              content
Hello World    ["Great"]             This is the content
Learn More     ["Learn", "Great"]    Learn about things

I know this is not the best way to store data like that, but it can't be changed at this point.

I want to get an array of unique categories in one query, some thing like this:

SELECT DISTINCT category FROM content

And end up with an array like this:

["Great", "Learn"]

I know it would be easy if the categories were in a separate table, but how would you do it if they are nested like this?

category is JSONB formatted.

like image 554
Jordash Avatar asked Aug 28 '26 19:08

Jordash


1 Answers

In Postgres, you can use array functions like;

select distinct unnest(category) as nestCategory from content

PostgreSQL Array Functions

like image 175
CanFil Avatar answered Aug 31 '26 17:08

CanFil



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!