Bird
0
0

Which of the following queries correctly uses JSONB existence operators to achieve this?

hard📝 Application Q8 of 15
PostgreSQL - JSON and JSONB

You need to retrieve all rows from the events table where the JSONB column metadata contains at least one of the keys 'user' or 'admin'. Which of the following queries correctly uses JSONB existence operators to achieve this?

ASELECT * FROM events WHERE metadata ? 'user' AND metadata ? 'admin';
BSELECT * FROM events WHERE metadata ? 'user' OR metadata ? 'admin';
CSELECT * FROM events WHERE metadata ?& ARRAY['user', 'admin'];
DSELECT * FROM events WHERE metadata ?| ARRAY['user', 'admin'];
Step-by-Step Solution
Solution:
  1. Step 1: Understand the operators

    ? checks a single key, ?| checks if any key in an array exists, ?& checks if all keys exist.
  2. Step 2: Identify the requirement

    We want rows where either 'user' or 'admin' key exists (any key).
  3. Step 3: Match the correct operator

    ?| matches any key in the array, so SELECT * FROM events WHERE metadata ?| ARRAY['user', 'admin']; is correct.
  4. Final Answer:

    SELECT * FROM events WHERE metadata ?| ARRAY['user', 'admin']; -> Option D
  5. Quick Check:

    Use ?| for any key existence in array [OK]
Quick Trick: Use ?| to check if any key exists in JSONB [OK]
Common Mistakes:
  • Using ?& which requires all keys to exist
  • Using multiple OR conditions instead of ?|
  • Confusing ? with ?| and ?& operators

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PostgreSQL Quizzes