Reputation: 4938
In our database we have a data set sorta like the following:
+----+-------------------------------+
| id | stuff |
+----+-------------------------------+
| 1 | {} |
+----+-------------------------------+
| 2 | {"a": "something", "b": null} |
+----+-------------------------------+
| 3 | {"c": null, "d": null} |
+----+-------------------------------+
I would like to match only, in this case, the one with id = 2
, reason being that at least one of the values in the object is not null.
How can this be done with PostgreSQL?
WHERE stuff != '{}'
but that of course only checks for an empty objectWHERE (stuff->>'a') IS NOT NULL
, but the thing is the list of keys in the objects are not hardcoded, could be anythingUpvotes: 1
Views: 276
Reputation: 121574
Use the function jsonb_each_text()
or json_each_text()
, example:
with my_table(id, jdata) as (
values
(1, '{}'::jsonb),
(2, '{"a": "something", "b": null}'),
(3, '{"c": null, "d": null}')
)
select distinct t.*
from my_table t
cross join jsonb_each_text(jdata)
where value is not null;
id | jdata
----+-------------------------------
2 | {"a": "something", "b": null}
(1 row)
This query (proposed by Abelisto, see the comments) should be more performant on a larger dataset:
select t.*
from my_table t
where exists (
select 1
from jsonb_each_text(jdata)
where value is not null);
Upvotes: 3