Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the SUM of values on a JSONB column

Tags:

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)
like image 514
AndreDurao Avatar asked Aug 23 '16 13:08

AndreDurao


People also ask

Can you index Jsonb Postgres?

JSONB and IndexesPostgreSQL can use indexes for the text results as compare operands. GIN index can be used by the GIN JSONB operator class.

Is Jsonb better than JSON?

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.

What is Jsonb column?

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.


1 Answers

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);
like image 197
Patrick Avatar answered Sep 23 '22 16:09

Patrick