patternsqlMinor
Check if property exists in an object inside array in JSONB field in Postgres
Viewed 0 times
fieldpostgresarrayobjectpropertyexistscheckjsonbinside
Problem
Here is my table data:
Corresponding sqlfiddle - http://sqlfiddle.com/#!17/e3f09
The question is - how do I select all records, where "f" property (path is the same everywhere - 'c -> d -> f') exists?
Corresponding sqlfiddle - http://sqlfiddle.com/#!17/e3f09
create table jsonData (
id serial primary key,
data jsonb
);
insert into jsonData (data) values (
${
"b": 2,
"c": [
{
"d": {
"e": true
}
},
{
"d": {
"e": true
}
},
{
"d": {
"e": true,
"f": "I'm here"
}
}
]
}
$::jsonb),
(
${
"a": 1,
"c": [
{
"d": {
"e": true
}
},
{
"d": {
"e": true
}
},
{
"d": {
"e": true
}
}
]
}$::jsonb);The question is - how do I select all records, where "f" property (path is the same everywhere - 'c -> d -> f') exists?
Solution
Use an
SQL Fiddle
EXISTS in which you use jsonb_array_elements() to get the arrays' elements and check ->'d'->'f' for NULL.SELECT *
FROM jsonData
WHERE EXISTS (SELECT *
FROM jsonb_array_elements(data->'c')
WHERE value->'d'->'f' IS NOT NULL);SQL Fiddle
Code Snippets
SELECT *
FROM jsonData
WHERE EXISTS (SELECT *
FROM jsonb_array_elements(data->'c')
WHERE value->'d'->'f' IS NOT NULL);Context
StackExchange Database Administrators Q#208488, answer score: 9
Revisions (0)
No revisions yet.