Skip to content
Advertisement

Performing division with PostgreSQL / json

I have written a simple query against a table in a Postgres database that contains a column “manifest” of type json. Each cell contains a very long value and I am extracting the numerical value for “size”.

I need to create a new column (perhaps call it “size in MB”), and perform division against size. Specifically, I need to take the value of size and divide it by 1024, two times. I have tried every example I can find to no avail.

Here is my current query, and a small snippet of the result:

The goal is to take image_size, divide by 1024 two times, and store the result in a new column called “size in MB”. So in this case, the result of the math would be 598.

Advertisement

Answer

To extract a scalar value (not another json) use the ->> operator (not ->).
That returns type text. So you also need to cast before doing math on the number:

See:

You could do integer division, which truncates, computing 598 like you projected:

Casting to a floating point number or numeric avoids integer division and shows your sample value to be much closer to 599:

The numeric constant 123 resolves to type integer, while 123.0 (containing a point .) resolves to numeric.
And 1024 * 1024 = 1048576 = 2^20.

Maybe round? Or keep two fractional digits?

But consider the built-in function pg_size_pretty() instead which is made for this very purpose:

So:

Should give you:

I also fixed a couple other issues with your query.

Assuming captured_at is type timestamptz (like it probably should be), current_date would introduce a dependency on time zone setting of the session, which is a sneaky, unnecessary source of corner-case errors. See:

And “name” is not a good name.

Advertisement