I've got a 1-dimension JSONB on postgresql like this:
SELECT '{"a": 1, "b": 2, "c": 3}'::jsonb;
How to get the SUM of values on a JSONB column? Like the sum of 1+2+3?
PostgreSQL has the jsonb_object_keys function, but I was looking for something like "jsonb_object_values" (I know that this function does not exists)
# select jsonb_object_keys( '{"a": 1, "b": 2, "c": 3}'::jsonb );
jsonb_object_keys
-------------------
a
b
c
(3 rows)
JSONB and IndexesPostgreSQL can use indexes for the text results as compare operands. GIN index can be used by the GIN JSONB operator class.
The json data type stores an exact copy of the input text, which processing functions must reparse on each execution; while jsonb data is stored in a decomposed binary format that makes it slightly slower to input due to added conversion overhead, but significantly faster to process, since no reparsing is needed.
The JSONB data type stores JSON (JavaScript Object Notation) data as a binary representation of the JSONB value, which eliminates whitespace, duplicate keys, and key ordering. JSONB supports GIN indexes.
The jsonb_each_text()
function expands a set of JSON objects into rows in (key, value)
format. Since it returns a set of rows, you should use it as a row source. Since it returns data in the text
format, you should cast it to the appropriate type before further processing.
SELECT sum(v::integer)
FROM jsonb_each_text('{"a": 1, "b": 2, "c": 3}'::jsonb) j(k,v);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With