I would like to count distinct values from someText property from nested jbson object, but I can’t figure out how properly do it. Any suggestions are appreciated.
This is my jbson object
{ options: [
{
"object": { "someText": "example1"}
},
{
"object": { "someText": "example2"}
},
{
"object": { "someText": "example3"}
}
]
}
This is my query:
SELECT COUNT(distinct option_tb) AS uniqueOptions FROM tableT
WHERE option_tb->'options'->0 IS NOT NULL
AND option_tb->'options'->>'object'-> 'someText' is not null
3
Answers
You can use set-returning
jsonb_path_query()
:This produces implicit lateral join with your table, each
option_tb
spawning one row per match found by the function. No match means no rows returned. You will end up counting all possible distinct values ofsomeText
in all rows. This also doesn’t mind varying jsonb structures with missing elements in some rows: demoNote that null comparison in JSONPath expressions works differently from plain SQL: in SQL
v=null
yieldsnull
regardless of thev
value. In JSONPath, it works likev is null
.You can use the
jsonb_array_elements()
function to turn a JSON array into rows :Demo here
Simply you can use operators and functions to achieve this for example: