Challenge - 5 Problems
JSONB Containment Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ query_result
intermediate2:00remaining
Check JSONB containment with simple key-value
Given the table
products with a details column of type JSONB, what rows will be returned by this query?SELECT id FROM products WHERE details @> '{"color": "red"}';PostgreSQL
CREATE TABLE products (id SERIAL PRIMARY KEY, details JSONB); INSERT INTO products (details) VALUES ('{"color": "red", "size": "M"}'), ('{"color": "blue", "size": "L"}'), ('{"color": "red", "size": "S"}');
Attempts:
2 left
💡 Hint
The @> operator checks if the left JSONB contains the right JSONB as a subset.
✗ Incorrect
The query filters rows where the JSONB column 'details' contains the key-value pair {"color": "red"}. Rows 1 and 3 have this pair, so they are returned.
❓ query_result
intermediate2:00remaining
Containment with nested JSONB objects
Consider a table
users with a JSONB column profile. Which rows will match this query?SELECT user_id FROM users WHERE profile @> '{"address": {"city": "Boston"}}';PostgreSQL
CREATE TABLE users (user_id SERIAL PRIMARY KEY, profile JSONB); INSERT INTO users (profile) VALUES ('{"name": "Alice", "address": {"city": "Boston", "zip": "02101"}}'), ('{"name": "Bob", "address": {"city": "Seattle", "zip": "98101"}}'), ('{"name": "Carol", "address": {"city": "Boston"}}');
Attempts:
2 left
💡 Hint
The @> operator works recursively on nested JSON objects.
✗ Incorrect
Rows 1 and 3 have 'address' objects containing the key-value pair {"city": "Boston"}, so they match the query.
📝 Syntax
advanced2:00remaining
Identify the syntax error in JSONB containment query
Which option contains a syntax error in the use of the JSONB containment operator @> in PostgreSQL?
Attempts:
2 left
💡 Hint
JSON keys and string values must be enclosed in double quotes.
✗ Incorrect
Option B lacks double quotes around the key 'status', which is invalid JSON syntax causing a syntax error.
❓ optimization
advanced2:00remaining
Optimize JSONB containment query for performance
Which option will improve performance of this query?
SELECT * FROM events WHERE metadata @> '{"type": "click"}';Attempts:
2 left
💡 Hint
PostgreSQL supports special indexes for JSONB containment queries.
✗ Incorrect
A GIN index on a JSONB column speeds up containment queries using @> by indexing the JSON keys and values efficiently.
🧠 Conceptual
expert2:00remaining
Understanding JSONB containment operator behavior
What is the result of this query?
SELECT '{"a": 1, "b": 2}'::jsonb @> '{"a": 1}';Attempts:
2 left
💡 Hint
The @> operator returns true if the left JSONB contains the right JSONB as a subset.
✗ Incorrect
The left JSONB contains the key-value pair {"a": 1}, so the operator returns true.