I would like to report a possible issue with the JSON_QUERY() function in PostgreSQL 17.3, which I encountered during testing.
Issue Description:
While working with JSON_QUERY(), I observed inconsistent behavior when handling missing or multiple values in JSON paths. Below are two specific cases where the function does not behave as expected:
Multiple Values Without Wrapper:
When using ERROR ON ERROR with a JSON path that returns multiple values, the query correctly throws an error.
However, when the ERROR ON ERROR clause is omitted, instead of throwing an error or returning a meaningful response, it simply returns an empty result.
Query:
SELECT JSON_QUERY( data, '$.profile.contacts.email[*]' ERROR ON ERROR
) FROM users;
Expected Behavior: Without ERROR ON ERROR, it should either return an array or provide a clear error message, instead of an empty response.
Handling Missing Keys with DEFAULT Clause:
When a JSON path does not exist in the input JSON, using the DEFAULT ... ON EMPTY clause correctly returns the default value.
However, if the DEFAULT ... ON EMPTY clause is not specified, instead of an explicit error or NULL, the function simply returns an empty result.
For both ON EMPTY and ON ERROR, specifying ERROR will cause an error to be thrown with the appropriate message. Other options include returning an SQL NULL, an empty array (EMPTY [ARRAY]), an empty object (EMPTY OBJECT), or a user-specified expression (DEFAULTexpression) that can be coerced to jsonb or the type specified in RETURNING. The default when ON EMPTY or ON ERROR is not specified is to return an SQL NULL value.