Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgresql - distinct values from jsonb array

I have the following jsonb array column (tags)

|name | tags (jsonb)   |
--------------------------------
|john | [ "foo", "bar" ]
|smith| [ "bar", "bat" ]
|adam | [ "foo", "dot" ]

How to get the distinct tags as follows ["foo", "bar", "bat", "dot"] ?

like image 909
Yans Avatar asked Jan 05 '23 18:01

Yans


2 Answers

This will solve your particular problem.

SELECT DISTINCT tag FROM
  (SELECT name, JSONB_ARRAY_ELEMENTS(tags) as b FROM my_table) AS foo;

however you have a bigger problem. Storing tags like this is a mistake that's repeated far too often. You should normalize your table. Please see Django JSONField inside ArrayField

like image 100
e4c5 Avatar answered Jan 07 '23 20:01

e4c5


The accepted solution works, but can be simplified:

SELECT DISTINCT JSONB_ARRAY_ELEMENTS_TEXT(tags) AS tag FROM yourtable;

Also, while it's true that this might be an anti-pattern in many cases, there are still valid uses for this, as long as you are aware of its drawbacks (joining and searching will be more difficult).

like image 27
svenema Avatar answered Jan 07 '23 22:01

svenema