0

Where data is JSONB column, I want to check if the key exists, normally I use:

SELECT id FROM users WHERE length(data->>'fingerprint_id') IS NULL;

Is there any better/shorter way to do this? since other alternative give incorrect result:

> SELECT id FROM users WHERE data->>'fingerprint_id' IS NULL;
ERROR:  operator does not exist: jsonb ->> boolean
LINE 1: SELECT id FROM users WHERE data->>'fingerprint_id' IS NULL;
                                       ^
HINT:  No operator matches the given name and argument type(s). You might need to add explicit type casts.

> SELECT id FROM users WHERE data->>'fingerprint_id' = '';
 id 
----
(0 rows)
Kokizzu
  • 24,974
  • 37
  • 137
  • 233

2 Answers2

1

Apparently, I just need to enclose the query with () before IS NULL

SELECT id FROM users WHERE (data->>'fingerprint_id') IS NULL;
Kokizzu
  • 24,974
  • 37
  • 137
  • 233
1

There is an explicit operator (?) for this purpose:

where data_jsonb ? 'key'

But be aware, that this might cause some DB abstraction layers (f.ex. JDBC) to falsely recognize ? as an input parameter's placeholder.

As a workaround, you could use the jsonb_exists(json, text) function directly (but your code will then depend on an undocumented function), or define a similar operator for this, like in this answer.

More details about the (data ->> 'key') IS NULL syntax can be found here.

Community
  • 1
  • 1
pozs
  • 34,608
  • 5
  • 57
  • 63