PostgreSQL error code
PostgreSQL error 22030
22030 is the SQLSTATE PostgreSQL reports for duplicate json object key value, in class 22, Data Exception.
| SQLSTATE | 22030 |
|---|---|
| Condition name | duplicate_json_object_key_value |
| Class | 22 — Data Exception |
Reproduce it, then fix it
Several products share a category, and json_object_agg_unique refuses repeated keys. Group first so each key appears once, with the values collected into an array. Run the broken query to see the error, then switch to the fixed one. Edit either freely; every run is rolled back.
SELECT json_object_agg_unique(category, name) FROM products;
SELECT json_object_agg(category, names) FROM ( SELECT category, json_agg(name) AS names FROM products GROUP BY category ) AS c;