0
0
PostgreSQLquery~5 mins

JSONB containment (@>) operator in PostgreSQL - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does the JSONB containment operator @> do in PostgreSQL?
It checks if the left JSONB value contains the right JSONB value. In other words, it returns true if the right JSONB is a subset of the left JSONB.
Click to reveal answer
beginner
Example: What will this query return?<br>SELECT '{"a":1, "b":2}'::jsonb @> '{"a":1}'::jsonb;
It will return true because the left JSONB contains the key-value pair {"a":1} from the right JSONB.
Click to reveal answer
intermediate
Can the @> operator be used to check if a JSONB array contains a specific element?
Yes, it can check if a JSONB array contains a specific element by using the element inside an array on the right side. For example, '[1,2,3]'::jsonb @> '[2]'::jsonb returns true.
Click to reveal answer
beginner
What will this query return?<br>SELECT '{"a":1, "b":2}'::jsonb @> '{"b":3}'::jsonb;
It will return false because the value for key "b" in the left JSONB is 2, which does not match the value 3 in the right JSONB.
Click to reveal answer
beginner
Why is the JSONB containment operator useful in real life?
It helps quickly find rows where JSONB columns contain specific data without extracting or parsing the whole JSON. This is useful for filtering data stored in flexible JSON formats.
Click to reveal answer
What does jsonb_col @> '{"key":"value"}' check?
AIf jsonb_col contains the key-value pair {"key":"value"}
BIf jsonb_col equals {"key":"value"}
CIf jsonb_col is contained in {"key":"value"}
DIf jsonb_col is an array
Which of these returns true?<br>SELECT '[1,2,3]'::jsonb @> '[2]'::jsonb;
Anull
Bfalse
Cerror
Dtrue
What will this return?<br>SELECT '{"a":1}'::jsonb @> '{"a":1, "b":2}'::jsonb;
Atrue
Berror
Cfalse
Dnull
Can @> operator be used to check nested JSON objects?
AYes, it checks nested objects as well
BNo, only top-level keys
COnly arrays, not objects
DOnly strings
What type of data does the @> operator work with?
AText data type
BJSONB data type
CInteger data type
DDate data type
Explain how the JSONB containment operator @> works in PostgreSQL.
Think about subset and containment in JSON data.
You got /4 concepts.
    Give an example query using @> to find rows where a JSONB column contains a specific key-value pair.
    Use a simple JSON object on the right side.
    You got /4 concepts.