Using SQL/JSON Path Queries

1. Understanding JSON Path Language

SymbolMeaning
$Root
@Current item (in filter)
.keyObject accessor
[*]All array elements
[idx]Index (0-based)
? (filter)Predicate

2. Using jsonb_path_query

SELECT * FROM jsonb_path_query(
  '{"users":[{"id":1},{"id":2}]}',
  '$.users[*].id'
);

3. Using jsonb_path_query_array

SELECT jsonb_path_query_array(payload, '$.items[*].sku') FROM events;

4. Using jsonb_path_query_first

SELECT jsonb_path_query_first(payload, '$.user.id') FROM events;

5. Using jsonb_path_exists

SELECT * FROM events WHERE jsonb_path_exists(payload, '$.user_id ? (@ > 100)');
FunctionReturns
jsonb_path_existsboolean
jsonb_path_matchboolean (path must return single boolean)

6. Using jsonb_path_match

SELECT * FROM events WHERE jsonb_path_match(payload, '$.active == true');

7. Using Path Accessors

SELECT jsonb_path_query(payload, 'strict $.user.email') FROM events;
SELECT jsonb_path_query(payload, 'lax $.users[*].email');
ModeBehavior
laxDefault; auto-unwraps arrays
strictError on missing/structural mismatch

8. Using Filter Expressions

SELECT jsonb_path_query(payload, '$.items[*] ? (@.price > 100)') FROM events;

9. Using Arithmetic in Paths

SELECT jsonb_path_query(payload, '$.items[*].price * $.qty');

10. Using Comparison Operators in Paths

OperatorUse
== != < <= > >=Compare values
&& ||Logical combine
like_regexPattern match

11. Using String Methods

MethodEffect
.size()Array length
.type()JSON type
.string()Cast to string
.double()Cast to number
.keyvalue()Object → key/value pairs

12. Passing Variables to Path Queries

SELECT jsonb_path_query(payload, '$.items[*] ? (@.price > $min)',
       '{"min": 100}'::jsonb) FROM events;