jsonb_deep_sum
jsonb_deep_sum · Recursively sum numeric fields in JSONB objects
Overview
| ID | Extension | Package | Version | Category | License | Language |
|---|---|---|---|---|---|---|
| 101018 | jsonb_deep_sum | jsonb_deep_sum | 0.0.2 | FUNC | MIT | C |
PostgreSQL · 10, 11, 12, 13, 14, 15, 16, 17, 18
Usage
Sources:
jsonb_deep_sum 0.0.2 recursively adds numeric leaves in JSON objects. It supplies a two-value function and an aggregate, making it useful for summing sparse, nested metric maps whose keys differ between rows.
Core Workflow
jsonb_deep_add(jsonb, jsonb) RETURNS jsonb merges objects recursively and adds numeric values at matching paths. Keys present on only one side are retained. jsonb_deep_sum(jsonb) uses that function as its transition step with {} as the initial state; SQL NULL input rows are skipped.
Data Contract and Limitations
Every JSON value traversed must be either an object or a number. Strings, booleans, JSON nulls, and arrays raise errors, and incompatible shapes at the same key are not a coercion mechanism. Validate documents before aggregation and keep units consistent for every repeated path.
The implementation directly walks PostgreSQL’s internal jsonb representation in C. Upstream examples tested PostgreSQL 12-era builds but do not publish a current major-version matrix; rebuild and run the regression suite against the exact server. Aggregation materializes a complete result object in backend memory, so high key cardinality or deeply nested documents can be expensive. For schema-stable metrics, typed columns generally provide clearer validation, indexing, and overflow handling.