SQL ? jsonb key-exists operator
config ? 'region' is true when the object has that key, or when the array contains that element. The existence test that GIN indexes actually serve.
- 類別
- Strings
- Returns
boolean- In this category
- 152 of 172
語法
jsonb ? text
jsonb ?| text[]
jsonb ?& text[]
Each block is a separate form. The support table and the examples show which engine takes which.
引擎支援
| 引擎 | Support | 備註 |
|---|---|---|
| SQL Server | Not built in | no operator; JSON_PATH_EXISTS on 2022+ |
| PostgreSQL | 是 | Supported under this name. |
| MySQL | Different name or syntax | JSON_CONTAINS_PATH is the twin |
| SQLite | Different name or syntax | json_type(doc, '$.key') IS NOT NULL |
| Oracle | Different name or syntax | JSON_EXISTS condition |
範例
PostgreSQL
SELECT * FROM settings WHERE config ? 'region';
PostgreSQL
SELECT * FROM settings WHERE config ?| array['region', 'zone'];
PostgreSQL
SELECT * FROM settings WHERE config->'tags' ? 'pro';
小知識
- ? on an object checks top-level keys and on an array checks string elements. A scalar string counts as itself: '"foo"'::jsonb ? 'foo' is true. Nested keys need -> first.
- JDBC and some drivers treat ? as a parameter placeholder: double it as ?? or call the underlying function jsonb_exists(config, 'region') instead.
- ->> IS NOT NULL looks equivalent but cannot use the GIN index, and differs on JSON null: a member set to null passes ? and fails IS NOT NULL.
Questions about ? (jsonb)
? or ->> IS NOT NULL?
? for existence: it uses the GIN index and counts JSON null as present. ->> IS NOT NULL for 'has a non-null value'. Different questions with different plans.
Why is my ? parameter a bind placeholder?
Driver parsing: JDBC eats ? as a parameter. Write ?? (the driver escape) or the function form jsonb_exists(col, 'key') to sidestep the parser entirely.
Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.
Related on SQLly
Cheat sheets for the engines that have it: PostgreSQL, MySQL, SQLite, Oracle.
Functions your engine actually has
SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.