Skip to content

Instantly share code, notes, and snippets.

@ChronSyn
Last active March 14, 2022 23:38
Show Gist options
  • Save ChronSyn/205f9263b7918592e32d62816f8f10b4 to your computer and use it in GitHub Desktop.
Save ChronSyn/205f9263b7918592e32d62816f8f10b4 to your computer and use it in GitHub Desktop.
Filtering JSONB data in Postgres
-- Postgres: How to find a matching element in a JSON array
--
-- Definitions:
-- - animal_size_in_mm: int = 50
-- - var_animal_type: string = "fish"
--
-- Data example:
--
-- [
-- { "animal_type": "fish", "name": "Bob", "animal_size": 48 },
-- { "animal_type": "fish", "name": "Simon", "animal_size": 54 },
-- { "animal_type": "spider", "name": "Mark", "animal_size": 28 },
-- { "animal_type": "spider", "name": "Chonk", "animal_size": 62 },
-- ]
--
(jsonb_path_query_first(
some_query_alias.some_jsonb_field,
'$[*] ? (@.animal_type == $animal_type_var)',
jsonb_build_object(
'animal_type_var', var_animal_type
)
)->>'animal_size')::int <= animal_size_in_mm::int
--
-- Will return the following results:
-- { "animal_type": "fish", "name": "Bob", "animal_size": 48 }
-- { "animal_type": "spider", "name": "Mark", "animal_size": 28 }
--
-- This is because both these entries have an animal_size <= 50
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment