1

I have a jsonb column in my table and data is in this format:

[
  {
    "id": 1,
    "DATA": {
      "a": "XXX",
      "key": "value1"
    }
  },
  {
    "id": 2,
    "DATA": {
      "a": "XXX",
      "key": "value2"
    }
  }
]

I would like to get the count of rows in which key = value1. I tried some queries like:

select count(t.id) 
from my_table t, 
jsonb_array_elements(summary->'DATA') elem 
where elem->>'key' = 'value1';

It returned 0 rows, though there are rows in db with that key value pair. Thanks in advance,

1 Answer 1

4

Use jsonb_array_elements() for the column summary as it is in the form of json array.

select count(distinct t.id) 
from my_table t
cross join jsonb_array_elements(summary) elem 
where elem->'DATA'->>'key' = 'value1';

Alternatively, you can get rid of the function using @> operator:

select count(t.id) 
from my_table t
where summary @> '[{"DATA":{"key":"value1"}}]'

The second solution should be faster.

Db<>fiddle.

4
  • thanks for the answer, but I have a doubt, I came to know about this query: where (summary @> '[{"DATA":{"key":"value1"}}]'), can you explain if this is correct or not? also output of these 2 queries is different. Commented May 16, 2020 at 19:31
  • @CodePhatGaya - see the updated answer, note I have added distinct in the first query.
    – klin
    Commented May 16, 2020 at 21:15
  • yes, that works, thanks for your help. Can you provide any useful resource to study json query in postgres? official postgres documentation is not helpful. Commented May 17, 2020 at 5:48
  • 1
    The official documentation is an absolute foundation that you must know. You'll find lots of good tips here at Stackoverflow. I can't recommend any other useful sources because I never needed them. Tutorials accidentally found on the web are of different quality.
    – klin
    Commented May 17, 2020 at 10:54

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.