How to Use @> Operator in PostgreSQL: Syntax and Examples
In PostgreSQL, the
@> operator checks if the left JSON or array contains the right JSON or array. It returns true if all elements or key-value pairs on the right exist inside the left operand. This operator is commonly used with JSONB and array data types for containment queries.Syntax
The @> operator tests if the left JSONB or array contains the right JSONB or array. It returns a boolean true or false.
- Left operand: JSONB or array value to search within.
- Right operand: JSONB or array value to check for containment.
sql
left_operand @> right_operand
Example
This example shows how to use @> with JSONB and arrays to check if one contains the other.
sql
SELECT '{"name": "Alice", "age": 30, "skills": ["SQL", "Python"]}'::jsonb @> '{"age": 30}'::jsonb AS contains_age; SELECT ARRAY[1, 2, 3, 4] @> ARRAY[2, 3] AS array_contains;
Output
contains_age
--------------
t
(1 row)
array_contains
----------------
t
(1 row)
Common Pitfalls
Common mistakes when using @> include:
- Using it on
jsontype instead ofjsonb. The operator only works withjsonb. - Confusing the order:
left @> rightmeans left contains right, not the other way around. - Trying to check partial matches on arrays without exact elements.
sql
/* Wrong: using json type */ SELECT '{"a":1}'::json @> '{"a":1}'::json; /* Right: use jsonb type */ SELECT '{"a":1}'::jsonb @> '{"a":1}'::jsonb;
Output
ERROR: operator does not exist: json @> json
LINE 1: SELECT '{"a":1}'::json @> '{"a":1}'::json;
^
contains
----------
t
(1 row)
Quick Reference
| Operator | Description | Supported Types |
|---|---|---|
| @> | Checks if left JSONB or array contains right JSONB or array | jsonb, array |
| <@ | Checks if left JSONB or array is contained by right JSONB or array | jsonb, array |
Key Takeaways
The @> operator checks if the left JSONB or array contains the right JSONB or array.
Use @> only with jsonb or array data types, not with json.
The operator returns true if all elements or key-value pairs on the right exist in the left operand.
Remember the order: left @> right means left contains right, not vice versa.
Use @> for efficient containment queries in PostgreSQL.