HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlMinor

possible to query a database for an empty jsonb

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
queryemptydatabasepossibleforjsonb

Problem

I have a table in Postgres 9.6 db that is structured like this:

Table "public.pricings"
Column           |            Type             |                       Modifiers                       
---------------------------+-----------------------------+-------------------------------------------------------
id                        | integer                     | not null default nextval('pricings_id_seq'::regclass)
unconfirmed_matrix_prices | jsonb                       | not null default '"{}"'::jsonb


I'm new to using jsonb.

I'd like to search for any unconfirmed_matrix_prices that are empty(ie the default). I see I can do something like this:

solar_dev=# select count(*) from json_object_keys('{"f1":1,"f2":2}');
 count 
-------
     2
(1 row)


Is there a way I can do a where phrase where json_object_keys is equal to 0? I know a bit of a runaround way - Is there a better way?

Solution

You can simply check if the value is the default value, e.g.:

select *
from pricings
where unconfirmed_matrix_prices = '"{}"';


Note that an empty jsonb value should be written down as '{}', so the default value is not an empty jsonb. This may be problematic with some kind of queries, e.g. using the function jsonb_each(). I'd suggest to correct the default value in the way like this:

alter table pricings alter unconfirmed_matrix_prices set default '{}';
update pricings
set unconfirmed_matrix_prices = '{}'
where unconfirmed_matrix_prices = '"{}"';

Code Snippets

select *
from pricings
where unconfirmed_matrix_prices = '"{}"';
alter table pricings alter unconfirmed_matrix_prices set default '{}';
update pricings
set unconfirmed_matrix_prices = '{}'
where unconfirmed_matrix_prices = '"{}"';

Context

StackExchange Database Administrators Q#188969, answer score: 9

Revisions (0)

No revisions yet.