In PostgreSQL, the <@
operator checks to see whether the second array contains the first array. That is, whether or not the array on the right of the operator contains all elements in the array to the left.
The function returns a Boolean result: It returns true
if the second array contains the first array, and false
if it doesn’t. If the result is unknown, it returns NULL
.
Example
Here’s a basic example to demonstrate:
SELECT ARRAY[1,3] <@ ARRAY[1,2,3];
Result:
t
In this example, all elements in the first array are also in the second array, and so the <@
operator returned t
(true).
Here’s example of getting false:
SELECT ARRAY[1,3,4] <@ ARRAY[1,2,3];
Result:
f
We got f
(false) because 4
isn’t in the second array. All elements in the first array must be in the second array for the result to be true.
Here are some more examples:
SELECT
ARRAY[1,3] <@ ARRAY[1,2,3] AS "1",
ARRAY[1,2,3] <@ ARRAY[1,3] AS "2",
ARRAY[ARRAY[1,3]] <@ ARRAY[1,2,3] AS "3",
ARRAY[1,1+2] <@ ARRAY[1,2,3] AS "4",
ARRAY[1,30] <@ ARRAY[1,2,3] AS "5";
Result:
1 | 2 | 3 | 4 | 5
---+---+---+---+---
t | f | t | t | f
Negate the Operator
We can negate the condition with the NOT
operator:
SELECT
ARRAY[1,3] <@ ARRAY[1,2,3] AS "Original",
NOT ARRAY[1,3] <@ ARRAY[1,2,3] AS "Negated";
Result:
Original | Negated
----------+---------
t | f
Non Arrays
If either of the expressions are non arrays we get an error:
SELECT ARRAY[1,2,3] <@ 1;
Result:
ERROR: operator does not exist: integer[] <@ integer
LINE 1: SELECT ARRAY[1,2,3] <@ 1;
^
HINT: No operator matches the given name and argument types. You might need to add explicit type casts.
NULL Expressions
If any of the expressions resolve to NULL
, then NULL
is returned:
SELECT ARRAY[1,2,3] <@ NULL;
Result:
NULL