How to get size of PostgreSQL jsonb field?
Asked Answered
G

3

63

I have a table with jsonb field in table.

CREATE TABLE data.items
(
  id serial NOT NULL,
  datab jsonb
)

How to get size of this field in a query like this:

select id, size(datab) from data.items
Gin answered 5/11, 2016 at 16:17 Comment(2)
This can help you #12395038Rale
pg_column_size() or pg_size_bytes() postgresql.org/docs/current/static/…Essentialism
L
96

For the number of bytes used to store:

select id, pg_column_size(datab) from data.items;

For the number of elements on the jsonb object:

select id, jsonb_array_length(datab) from data.items;
Load answered 18/9, 2017 at 8:0 Comment(3)
pg_column_size returns "Number of bytes used to store a particular value (possibly compressed)" for the curious postgresql.org/docs/12/functions-admin.htmlKeyser
is there a similar function that will return the number of elements in a jsonb[] object?Cusk
the second one only works for json arrays, not objectsBorkowski
E
11

If the column uses EXTENDED storage (TOAST compression), you should use octet_length(datab::text) instead of pg_column_size

Ethyne answered 13/1, 2022 at 10:1 Comment(1)
OP didn’t indicate whether the desired result is (compressed) size on disk or (uncompressed) size of the object. octet_length is uncompressed size, which seems more useful to me.Sprinkle
C
0

To count the json string size:

select length(jsonb_field::text) from test;
Chronoscope answered 23/11, 2023 at 14:8 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.