0
0
PostgreSQLquery~20 mins

JSONB containment (@>) operator in PostgreSQL - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
JSONB Containment Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
query_result
intermediate
2: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"}');
ARows with id 1 and 3
BRows with id 2 only
CRows with id 1, 2, and 3
DNo rows returned
Attempts:
2 left
💡 Hint
The @> operator checks if the left JSONB contains the right JSONB as a subset.
query_result
intermediate
2: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"}}');
AUsers with user_id 1 and 3
BUser with user_id 2 only
CUsers with user_id 1, 2, and 3
DNo users returned
Attempts:
2 left
💡 Hint
The @> operator works recursively on nested JSON objects.
📝 Syntax
advanced
2: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?
ASELECT * FROM orders WHERE data @> '{"status": "shipped"}';
BSELECT * FROM orders WHERE data @> '{status: "shipped"}';
C;'}"deppihs" :"sutats"{' >@ atad EREHW sredro MORF * TCELES
DSELECT * FROM orders WHERE data @> '{"status":"shipped"}';
Attempts:
2 left
💡 Hint
JSON keys and string values must be enclosed in double quotes.
optimization
advanced
2:00remaining
Optimize JSONB containment query for performance
Which option will improve performance of this query?

SELECT * FROM events WHERE metadata @> '{"type": "click"}';
AUse a sequential scan with ANALYZE
BAdd a B-tree index on the metadata column
CCreate a GIN index on the metadata column
DRewrite the query using LIKE operator
Attempts:
2 left
💡 Hint
PostgreSQL supports special indexes for JSONB containment queries.
🧠 Conceptual
expert
2:00remaining
Understanding JSONB containment operator behavior
What is the result of this query?

SELECT '{"a": 1, "b": 2}'::jsonb @> '{"a": 1}';
ANULL
Bfalse
CSyntax error
Dtrue
Attempts:
2 left
💡 Hint
The @> operator returns true if the left JSONB contains the right JSONB as a subset.