Bird
0
0

You have a JSONB column info storing user preferences with nested keys. How can you efficiently query users who prefer dark mode stored as {"theme":{"mode":"dark"}}?

hard📝 Application Q8 of 15
PostgreSQL - JSON and JSONB
You have a JSONB column info storing user preferences with nested keys. How can you efficiently query users who prefer dark mode stored as {"theme":{"mode":"dark"}}?
AUse LIKE operator on JSON text: WHERE info::text LIKE '%dark%'
BExtract nested key with -> and compare: WHERE info->'theme'->>'mode' = 'dark'
CUse the JSONB containment operator: WHERE info @> '{"theme":{"mode":"dark"}}'
DCast JSONB to text and compare: WHERE info::text = '{"theme":{"mode":"dark"}}'
Step-by-Step Solution
Solution:
  1. Step 1: Understand JSONB containment operator

    @> checks if left JSONB contains right JSONB, efficient for nested queries.
  2. Step 2: Compare options

    Use the JSONB containment operator: WHERE info @> '{"theme":{"mode":"dark"}}' uses @> with exact nested JSON, best for performance and accuracy.
  3. Final Answer:

    Use the JSONB containment operator: WHERE info @> '{"theme":{"mode":"dark"}}' -> Option C
  4. Quick Check:

    Use @> for efficient nested JSONB queries [OK]
Quick Trick: Use @> to check nested JSONB contains key-value pairs [OK]
Common Mistakes:
  • Using LIKE on JSON text is slow and error-prone
  • Casting JSONB to text loses query efficiency
  • Using -> operator only extracts one level

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PostgreSQL Quizzes