33

I have a table 'Documents' which has a column 'Tags' with 'jsonb' datatype. Sample data in Tags column

 [{"Tag": "Social Media"}, {"Tag": "Adobe Creative"}]
 [{"Tag": "Interactive"}]
 [{"Tag": "Web 2.0"}, {"Tag": "Adobe Creative"},{"Tag": "Suite"}]

I need to get the distinct values of "Tag" like

 Social Media 
 Adobe Creative
 Interactive
 Web 2.0
 Suite

I am new in PostgreSQL.

1

3 Answers 3

34

The shortest version would be:

SELECT DISTINCT value->'Tag' AS tag
FROM Documents, jsonb_array_elements(Documents.Tags);

The jsonb_array_elements() function unnests the JSONB array into a set of rows with a single column called "value". It uses an implicit "lateral join" on the Documents table.

This gives you the distinct tags as jsonb values. If you want them as a text value, use the ->> operator instead of ->.

Sign up to request clarification or add additional context in comments.

3 Comments

If I need to add a where condition with this jsonb data type ,what shall I do? Eg. select * from documents where tags->'Tag' = 'Suite'
If I understand your question correctly, then the answer is no, because you can not directly access computed field values in the select list as filter conditions. You would either need to repeat the function calls or - probably easier in your case - use the above as a sub-query and then filter in the main query. In either case, you should use the ->> operator to get the text version of the JSON object.
SELECT * FROM documents, jsonb_array_elements( documents.tags ) AS elem WHERE elem->>'Tag' = 'Suite'; From this I got the required result. Thank you
19

since Postgres 9.6+

SELECT DISTINCT
  Tags->>'Tag'
FROM Documents;

2 Comments

Best answer imho, also drops the quotes around the actual value
This does not work with the OP example where tags is an array
12

you can also use the following snippet.

SELECT DISTINCT
  Tags::json->'Tag'
FROM Documents;

1 Comment

This does not work at all, and even with jsonb does not work with the OP example where tags is an array

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.