ANY And ALL Quantified Comparisons

Compare one value against a whole list with ANY and ALL: = ANY mirrors IN, <> ALL excludes a set, and subqueries can supply the operand.

SqlData Fetching

Code

snippet
-- = ANY(ARRAY[...]) 语义等价于 IN,但右操作数可以是任意数组表达式
SELECT order_id, status
FROM (VALUES
    (1, 'paid'),
    (2, 'shipped'),
    (3, 'cancelled'),
    (4, 'refunded')
) AS orders(order_id, status)
WHERE status = ANY (ARRAY['paid', 'shipped']);

-- <> ALL:与列表中每一项都不相等才通过
SELECT order_id, status
FROM (VALUES
    (1, 'paid'),
    (2, 'cancelled')
) AS orders(order_id, status)
WHERE status <> ALL (ARRAY['cancelled', 'refunded']);

-- ANY/ALL 前面可以接任意比较运算;子查询也是合法右操作数
SELECT order_id, amount
FROM (VALUES
    (1, 120),
    (2, 45),
    (3, 80)
) AS orders(order_id, amount)
WHERE amount > ALL (SELECT unnest(ARRAY[100, 60]));

How it works

Three SELECT statements over inline VALUES lists demonstrate the quantified comparison operators. The first uses WHERE status = ANY (ARRAY['paid', 'shipped']) — the comment notes this is semantically equivalent to IN, but the right operand can be any array expression — so from the four order rows it returns the paid and shipped rows (orders 1 and 2).

The second uses WHERE status <> ALL (ARRAY['cancelled', 'refunded']), which passes only when the value differs from every list item — of the two rows offered, only paid (order 1) survives. The third shows the comparison operator being swapped freely: WHERE amount > ALL (SELECT unnest(ARRAY[100, 60])) keeps only amounts greater than every subquery value, so of 120, 45, and 80 only order 1’s amount 120 qualifies.

What to watch for

  • The right operand of ANY/ALL need not be a literal array: the third statement feeds it a subquery (SELECT unnest(...)) instead, per the file’s comment that subqueries are valid operands.
  • <> ALL and = ANY are not mirror images — one requires inequality against every element, the other a single equality match.

Using it

Each statement aliases its inline rows as orders(order_id, status) or orders(order_id, amount), so the three demonstrations run as-is and return, in order: the two paid/shipped orders, the single non-cancelled order, and the single order whose amount beats every threshold.

Key statements

SELECT order_id, amount
FROM (VALUES
(1, 120),
(2, 45),
(3, 80)
) AS orders(order_id, amount)
WHERE amount > ALL (SELECT unnest(ARRAY[100, 60]));
SELECT order_id, status
FROM (VALUES
(1, 'paid'),
(2, 'shipped'),
(3, 'cancelled'),
(4, 'refunded')
) AS orders(order_id, status)
WHERE status = ANY (ARRAY['paid', 'shipped']);
SELECT order_id, status
FROM (VALUES
(1, 'paid'),
(2, 'cancelled')
) AS orders(order_id, status)
WHERE status <> ALL (ARRAY['cancelled', 'refunded']);

Interactive Tools for This Topic