0
0
PostgreSQLquery~10 mins

JSONB existence (?) operator in PostgreSQL - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - JSONB existence (?) operator
Start with JSONB column
Apply ? operator with key
Check if key exists in JSONB
Return TRUE
Return FALSE
The ? operator checks if a specified key exists in a JSONB column and returns true or false.
Execution Sample
PostgreSQL
SELECT data ? 'name' AS has_name FROM users;
This query checks if the key 'name' exists in the JSONB column 'data' for each row in 'users'.
Execution Table
Rowdata (JSONB)Key CheckedCondition (key exists?)Result (TRUE/FALSE)
1{"name": "Alice", "age": 30}nameExistsTRUE
2{"age": 25, "city": "NY"}nameDoes not existFALSE
3{"name": "Bob", "city": "LA"}nameExistsTRUE
4{"city": "Chicago"}nameDoes not existFALSE
💡 All rows checked; query returns TRUE if key exists, FALSE otherwise.
Variable Tracker
VariableStartRow 1Row 2Row 3Row 4
dataN/A{"name": "Alice", "age": 30}{"age": 25, "city": "NY"}{"name": "Bob", "city": "LA"}{"city": "Chicago"}
keyN/Anamenamenamename
resultN/ATRUEFALSETRUEFALSE
Key Moments - 2 Insights
Why does the query return FALSE for row 2 even though the JSONB has other keys?
Because the ? operator checks only for the specific key 'name'. Row 2's JSONB does not have 'name', so it returns FALSE as shown in execution_table row 2.
Can the ? operator check for nested keys inside JSON objects?
No, the ? operator only checks for top-level keys in the JSONB column. Nested keys require different functions like jsonb_path_exists.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the result for row 3?
AFALSE
BTRUE
CNULL
DError
💡 Hint
Check the 'Result' column for row 3 in the execution_table.
At which row does the key 'name' NOT exist according to the execution_table?
ARow 1
BRow 2
CRow 3
DRow 4
💡 Hint
Look at the 'Condition' column for rows where it says 'Does not exist'.
If the key checked was changed to 'city', what would be the result for row 1?
ATRUE
BNULL
CFALSE
DError
💡 Hint
Refer to the 'data' JSONB in row 1 and check if 'city' key exists.
Concept Snapshot
JSONB existence (?) operator:
- Syntax: jsonb_column ? 'key'
- Returns TRUE if 'key' exists at top-level in JSONB
- Returns FALSE if 'key' is missing
- Only checks top-level keys, not nested
- Useful for quick key presence checks in JSONB columns
Full Transcript
The JSONB existence operator (?) in PostgreSQL checks if a specific key exists in a JSONB column. For each row, it looks at the JSONB data and returns TRUE if the key is present at the top level, otherwise FALSE. This operator does not check nested keys inside objects. For example, if the JSONB column has {"name": "Alice"}, checking for 'name' returns TRUE. If the key is missing, it returns FALSE. This is useful to filter or find rows containing certain keys in JSONB data.