Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query Postgres JSONB where key doesn't exist

Given a set of data.

1 | { 'completed': true }
2 | { 'office_completed': false }

Is there a way to query office_completed != 'true' and have it return both records? Or a way to select all records that DON'T have the office_completed key? I can query all records which have the office_completed key with:

SELECT * FROM jsonb WHERE data ? 'office_completed';

But couldn't find a way to pull the opposite.

What brings me to this problem is that I have a data set that may or may not have the office_completed key and I need to query all records that have office_completed != 'true' but if the key doesn't exist I get nothing from it. If the key doesn't exist, I'd think that would count as !=true but it apparently doesn't. :-) I figured the alternative would be to select all records that don't have the office_completed key OR office_completed != 'true' but can't figure out how to do that.

I appreciate it if somebody has a better idea for this. Thanks!

like image 762
andyrue Avatar asked Aug 18 '16 20:08

andyrue


People also ask

How do you check if a key exists in JSON in Postgres?

In Postgres, if you select a key that does not exist it will return null. so u can check the existence of a key by checking the null value of that key.

Can you index Jsonb Postgres?

It is a decomposed binary format to store JSON. JSONB supports indexing the JSON data, and is very efficient at parsing and querying the JSON data. In most cases, when you work with JSON in PostgreSQL, you should be using JSONB.


1 Answers

Just for reference for previous post.

Simply using NOT() like that if want to find all record don't have key:

SELECT * FROM jsonb WHERE NOT( data ? 'office_completed' );
like image 86
Kristo Mägi Avatar answered Sep 24 '22 08:09

Kristo Mägi