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)
4

2 回答 2

1

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

SELECT id FROM users WHERE (data->>'fingerprint_id') IS NULL;
于 2015-01-22T06:17:27.413 回答
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.

于 2015-01-22T09:43:08.917 回答