Bird
0
0

You want to filter rows where the JSONB column config contains the key 'enabled' but only if the value is true. Which query correctly combines JSONB existence and value check?

hard📝 Application Q9 of 15
PostgreSQL - JSON and JSONB
You want to filter rows where the JSONB column config contains the key 'enabled' but only if the value is true. Which query correctly combines JSONB existence and value check?
ASELECT * FROM settings WHERE config ? 'enabled' AND config->>'enabled' = 'true';
BSELECT * FROM settings WHERE config ? 'enabled' OR config->>'enabled' = 'true';
CSELECT * FROM settings WHERE config @> '{"enabled": false}';
DSELECT * FROM settings WHERE config ? 'enabled' AND config->'enabled' = true;
Step-by-Step Solution
Solution:
  1. Step 1: Understand the requirement

    We want rows where the key 'enabled' exists and its value is true.
  2. Step 2: Analyze each option

    SELECT * FROM settings WHERE config ? 'enabled' AND config->>'enabled' = 'true'; checks key existence with ? and then compares the value as text to 'true'. SELECT * FROM settings WHERE config ? 'enabled' OR config->>'enabled' = 'true'; uses OR which is incorrect logic. SELECT * FROM settings WHERE config @> '{"enabled": false}'; uses containment operator but for incorrect value (false). SELECT * FROM settings WHERE config ? 'enabled' AND config->'enabled' = true; compares JSONB value directly to boolean true which is invalid syntax.
  3. Final Answer:

    SELECT * FROM settings WHERE config ? 'enabled' AND config->>'enabled' = 'true'; -> Option A
  4. Quick Check:

    Combine ? for key and ->> for value check [OK]
Quick Trick: Use ? for key and ->> for value comparison [OK]
Common Mistakes:
  • Using OR instead of AND
  • Comparing JSONB value directly to boolean
  • Relying only on containment operator

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PostgreSQL Quizzes