Using SQL/JSON Path Queries
1. Understanding JSON Path Language
| Symbol | Meaning |
| $ | Root |
| @ | Current item (in filter) |
| .key | Object 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)');
| Function | Returns |
| jsonb_path_exists | boolean |
| jsonb_path_match | boolean (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');
| Mode | Behavior |
| lax | Default; auto-unwraps arrays |
| strict | Error 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
| Operator | Use |
| == != < <= > >= | Compare values |
| && || | Logical combine |
| like_regex | Pattern match |
11. Using String Methods
| Method | Effect |
| .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;