Sub topic 7
Filtering rows: @>, <@, &&, ANY and ALL
This chapter covers how to write WHERE clauses against array columns. It assumes you can already declare an array column, write values with ARRAY[...] or '{...}', and read the three-valued logic of NULL in a WHERE clause. It also assumes you can run SQL in psql or another PostgreSQL client.
Setup
The examples use two small tables. Run this once to follow along.
CREATE TABLE posts (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
title text NOT NULL,
tags text[] NOT NULL DEFAULT '{}'
);
INSERT INTO posts (title, tags) VALUES
('Intro to arrays', ARRAY['sql', 'postgres']),
('Indexing', '{postgres,indexing,gin}'),
('Window functions', '{sql,analytics}'),
('Untagged draft', '{}');
CREATE TABLE quizzes (
student text PRIMARY KEY,
scores int[] NOT NULL
);
INSERT INTO quizzes (student, scores) VALUES
('Ana', '{70,85,90}'),
('Ben', '{55,80}'),
('Cy', '{}');Two families of tests
PostgreSQL gives you two families of array predicates. They look similar but answer different questions.
- Array-to-array operators (
@>,<@,&&) compare a whole array with another whole array. They ignore order and duplicates. - Scalar-versus-array constructs (
= ANY,<> ALL,> ALLand so on) compare one value with each element of an array and combine the results with OR (ANY) or AND (ALL).
| Expression | True when |
|---|---|
| `a @> b` | `a` contains every element of `b` |
| `a <@ b` | `a` is contained by `b` (every element of `a` appears in `b`) |
| `a && b` | `a` and `b` share at least one element |
| `x = ANY (a)` | at least one element of `a` equals `x` |
| `x <> ALL (a)` | no element of `a` equals `x` |
| `x > ALL (a)` | `x` is greater than every element of `a` |
Containment: @> and <@
a @> b reads "a contains b". It is true when every element of b appears somewhere in a.
SELECT id, title FROM posts WHERE tags @> ARRAY['postgres'];
SELECT id, title FROM posts WHERE tags @> ARRAY['sql', 'postgres'];The first query returns posts 1 and 2. The second returns only post 1, because a row must carry both tags.
<@ is the same test written the other way round: a <@ b is identical to b @> a. Use it when the fixed list is on the right and you want rows whose tags are a subset of that list.
SELECT id, title
FROM posts
WHERE tags <@ ARRAY['sql', 'postgres', 'analytics'];This returns posts 1, 3 and 4. Post 4 qualifies because an empty array is a subset of every array. If you mean "tagged, and only with these", add a guard:
SELECT id, title
FROM posts
WHERE tags <@ ARRAY['sql', 'postgres', 'analytics']
AND cardinality(tags) > 0;Containment treats arrays as sets of values. Order does not matter, and duplicates do not count:
SELECT
ARRAY['b', 'a'] @> ARRAY['a', 'b'] AS order_ignored,
ARRAY['a'] @> ARRAY['a', 'a'] AS duplicates_ignored,
ARRAY['a', 'b'] @> ARRAY[]::text[] AS contains_empty;All three columns are true.
Overlap: &&
a && b is true when the two arrays have at least one element in common. It is the usual way to ask "does this row have any of these tags?".
SELECT id, title FROM posts WHERE tags && ARRAY['gin', 'sql'];This returns posts 1, 2 and 3. && against an empty array is always false, and an empty column value never overlaps anything. Post 4 can never match an overlap test.
ANY and ALL
ANY and ALL take a comparison operator, a scalar on the left and an array in parentheses on the right. The operator is applied to the scalar and each element in turn.
-- Does this post carry the tag 'gin'?
SELECT id, title FROM posts WHERE 'gin' = ANY (tags);
-- Which students have at least one score of exactly 90?
SELECT student FROM quizzes WHERE 90 = ANY (scores);
-- Which students scored at least 60 on every quiz?
SELECT student FROM quizzes WHERE 60 <= ALL (scores);The last query returns Ana and Cy. Cy has no scores at all, so there is nothing to fail the test. That result is correct but rarely what you meant. If "has scores and all are at least 60" is the real requirement, add AND cardinality(scores) > 0.
ANY also has a long-standing synonym, SOME. The comparison can be any operator that works on the element type, including LIKE:
SELECT id, title
FROM posts
WHERE title LIKE ANY (ARRAY['Intro%', 'Index%']);Here the array holds patterns, and the scalar is the column. This helps when you would otherwise write a chain of OR conditions. It does not work in reverse. 'post%' LIKE ANY (tags) would treat the tags as the strings to be matched, which is the wrong way round. To match a pattern against each tag, expand the array first:
SELECT id, title
FROM posts AS p
WHERE EXISTS (
SELECT 1
FROM unnest(p.tags) AS t(tag)
WHERE t.tag LIKE 'post%'
);ANY with a list or a subquery
= ANY (array) is also how you pass a list of values as a single parameter. Instead of building IN ($1, $2, $3) with a variable number of placeholders, bind one array:
SELECT id, title
FROM posts
WHERE id = ANY ('{1,3}'::bigint[]);x = ANY (subquery) is another form that behaves like IN (subquery). These forms use the scalar column's ordinary B-tree index, not a GIN index.
Matching the element type
The array-to-array operators need both sides to have the same array type. A literal such as ARRAY['postgres'] has type text[], which matches the tags column. Problems appear when the types differ:
-- ids is bigint[]; ARRAY[1, 2] is integer[]
SELECT ARRAY[1, 2, 3]::bigint[] @> ARRAY[2]::bigint[];Without the casts, a bigint[] column compared to ARRAY[2] fails with "operator does not exist: bigint[] @> integer[]". The quoted form '{2}' avoids this, because an untyped literal takes the type of the other operand. When you pass a parameter from application code, write the cast explicitly, as in tags @> $1::text[].
A varchar[] column compared against ARRAY['postgres'] fails the same way, because text[] and varchar[] are different types. Cast the literal with ARRAY['postgres']::varchar[].
NULLs and empty arrays in predicates
Three-valued logic applies to every predicate in this chapter. Test these on literals to see the exact results:
SELECT
1 = ANY (ARRAY[1, NULL]) AS found_with_null,
1 = ANY (ARRAY[2, NULL]) AS missing_with_null,
1 <> ALL (ARRAY[2, NULL]) AS not_in_with_null,
1 = ANY ('{}'::int[]) AS any_empty,
1 <> ALL ('{}'::int[]) AS all_empty,
ARRAY[1, NULL] @> ARRAY[NULL]::int[] AS contains_null,
ARRAY[1, NULL] && ARRAY[NULL]::int[] AS overlaps_null;| Column | Result | Why |
|---|---|---|
| `found_with_null` | `true` | One element matched, so the OR is true. |
| `missing_with_null` | `NULL` | No match, but comparing with the `NULL` element is unknown. |
| `not_in_with_null` | `NULL` | Same cause as `NOT IN` with a `NULL` in the list. |
| `any_empty` | `false` | OR over zero comparisons is false. |
| `all_empty` | `true` | AND over zero comparisons is true. |
| `contains_null` | `false` | `NULL` is never equal to anything, including `NULL`. |
| `overlaps_null` | `false` | Same reason. |
A WHERE clause keeps only rows where the condition is true. A NULL result drops the row, just as false does. This matters when you negate a predicate. If tags can be NULL, then NOT tags @> ARRAY['gin'] is also NULL for that row, and the row disappears from both the positive and negated queries. Our tags column is NOT NULL, so this does not happen here. On a nullable column, use IS DISTINCT FROM logic or COALESCE(tags, '{}') when you need rows with no array to count as "does not contain".
Because NULL elements never match, you cannot look for a NULL inside an array with @> or = ANY. Use array_position(arr, NULL), which does treat NULL as a searchable value, or expand the array and test IS NULL.
The whole-array operator = behaves differently. ARRAY[1, NULL] = ARRAY[1, NULL] is true, since array equality treats two NULL elements as the same. It is order-sensitive and requires equal length.
Negation patterns
Negated searches are easy to get subtly wrong.
-- Posts that do NOT have the tag 'sql'
SELECT id, title FROM posts WHERE NOT (tags @> ARRAY['sql']);
-- Equivalent with ALL: every tag differs from 'sql'
SELECT id, title FROM posts WHERE 'sql' <> ALL (tags);
-- Posts with none of these tags
SELECT id, title FROM posts WHERE NOT (tags && ARRAY['sql', 'gin']);The first two queries return posts 2 and 4. The <> ALL form returns post 4 as well, because an empty array passes vacuously. Both forms treat the empty array as "does not have the tag", which is usually what you want. The third query returns post 4 only.
Index support
A GIN index on the array column serves @>, <@, && and =. It does not serve = ANY (column):
CREATE INDEX posts_tags_gin ON posts USING gin (tags);
-- Can use posts_tags_gin
EXPLAIN SELECT id FROM posts WHERE tags @> ARRAY['gin'];
-- Cannot use posts_tags_gin; scans every row
EXPLAIN SELECT id FROM posts WHERE 'gin' = ANY (tags);For a single value, rewrite 'gin' = ANY (tags) as tags @> ARRAY['gin'] so the planner can use the index. On a table with four rows the planner will pick a sequential scan whichever form you use, because reading the table is cheaper than reading the index. Judge index use on a realistically sized table. The next chapters on GIN indexes go into more detail.
<@ can use a GIN index, but it is often a poor fit. An index can quickly find rows containing a given value, but "contains only values from this list" requires visiting rows that match no value at all, such as empty arrays.
Common mistakes
- Using
= ANYon a large table and expecting an index. Rewrite single-value checks as@>. - Forgetting that
@>means all.tags @> ARRAY['a', 'b']requires both. Use&&for either. - Reading
<@as "has some of". It means "has only values from". - Mismatched element types. Cast the literal or parameter to the column's array type.
- Empty arrays in
<@and<> ALL. They match vacuously. Addcardinality(col) > 0if untagged rows should be excluded. - Searching for
NULLelements with@>or= ANY. It never matches.
Exercises
Exercise
Write a query that returns the ids of posts tagged with both 'sql' and 'analytics', and a second query that returns posts tagged with either of them. Which posts does each return in the sample data?
Show answer
Both: SELECT id FROM posts WHERE tags @> ARRAY['sql', 'analytics']; returns only post 3. Either: SELECT id FROM posts WHERE tags && ARRAY['sql', 'analytics']; returns posts 1 and 3.
Exercise
In the quizzes table, list students whose lowest score is at least 60 and who have at least one score. Which student is returned, and why does the cardinality guard matter?
Show answer
SELECT student FROM quizzes WHERE 60 <= ALL (scores) AND cardinality(scores) > 0; returns only Ana. Without the guard Cy would also be returned, because ALL over an empty array is true. Ben is excluded because 55 is below 60.
Exercise
A query uses WHERE 'gin' = ANY (tags) on a table with millions of rows and a GIN index on tags, but EXPLAIN shows a sequential scan. How do you fix it, and what does the fixed query return when a row's tags column is an empty array?
Show answer
Rewrite it as WHERE tags @> ARRAY['gin'] so the GIN index can be used (cast the literal to the column's element type if needed). An empty array does not contain 'gin', so that row is not returned by either form.