7

I have a query like

SELECT DISTINCT (value->'Tag') AS tagname 
FROM documents, 
     jsonb_array_elements(documents.Tags)

so the tagname is a jsonb value. I need to cast that tagname to varchar. How do I do that cast?

sample data in Tags column in documents table is

'[{"Tag":"Web 2.0"},{"Tag":"Adobe Creative"},{"Tag":"Suite"}]'

I am working on java jpa. I tried the native query as

Query query = this.em.createNativeQuery(
            "select distinct (value->'Tag')::varchar as tags from documents, jsonb_array_elements(documents.Tags)");

but its showing

Not all named parameters have been set:

1 Answer 1

13

No need for a cast, simply use the ->> operator which returns the value as text

SELECT DISTINCT value ->> 'Tag' AS tagname 
FROM documents, 
     jsonb_array_elements(documents.tags);

As you might need a cast for something different someday:

:: isn't the only way to cast a value (and which is what JPA chokes on). You can also use the standard cast() operator:

SELECT DISTINCT cast(value -> 'Tag' as varchar) AS tagname 

But the ->> operator is the better choice here.

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

Comments

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.