3

I'm trying to find which of the jsonb keys are the most popular ones in my data field. I was able to get names of all keys with this query:

select jsonb_object_keys(data) as key
from client 
group by key;

When I try to add a count like I normally do:

select jsonb_object_keys(data) as key, count(jsonb_object_keys(data))
from client 
group by key;

I receive this error:

ERROR: aggregate function calls cannot contain set-returning function calls

Is there a way to count distinct keys of jsonb object?

Sample data:

data
{"a": "xyz"}
{"b": "assa", "c": "134323"}
{"c": "123"}
{"c": "12324", "a": "xysaz"}

Desired output:

key count(key)
a   2
b   1  
c   3
1
  • Please provide sample data and desired results. Commented Feb 25, 2020 at 11:07

1 Answer 1

6

jsonb_object_keys is a set returning function -- basically a table. You want to refer to it in the FROM clause, so I recommend:

select k as key, count(*)
from client c cross join lateral
     jsonb_object_keys(c.data) k
group by k;

The lateral is actually optional. However, I much prefer including it because otherwise the parsing is awkward (why does c.data resolve correctly?).

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

1 Comment

honestly, this was some black magic. i never new about lateral and this has changed my life. so awesome. thank you!

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.