ANY and ALL help you check if a value matches some or all items in a list. This makes it easy to compare one value against many at once.
ANY and ALL with arrays in PostgreSQL
SELECT column_name FROM table_name WHERE column_name operator ANY (array_expression); SELECT column_name FROM table_name WHERE column_name operator ALL (array_expression);
operator can be =, <, >, <=, >=, <> etc.
ANY means the condition is true if it matches at least one element in the array.
ALL means the condition must be true for every element in the array.
SELECT * FROM products WHERE price = ANY (ARRAY[10, 20, 30]);
SELECT * FROM products WHERE price > ALL (ARRAY[5, 7, 9]);
SELECT * FROM users WHERE username = ANY (ARRAY[]::text[]);
SELECT * FROM orders WHERE quantity <= ALL (ARRAY[100]);
This creates a products table and adds four fruits with prices. Then it finds products priced at 10 or 30 using ANY. Next, it finds products priced greater than both 15 and 25 using ALL.
CREATE TABLE products (id SERIAL PRIMARY KEY, name TEXT, price INT); INSERT INTO products (name, price) VALUES ('Apple', 10), ('Banana', 20), ('Cherry', 30), ('Date', 40); -- Find products with price equal to any in the list SELECT name, price FROM products WHERE price = ANY (ARRAY[10, 30]); -- Find products with price greater than all in the list SELECT name, price FROM products WHERE price > ALL (ARRAY[15, 25]);
ANY returns true if the condition matches at least one element in the array.
ALL returns true only if the condition matches every element in the array.
Using an empty array with ANY always returns false; with ALL it returns true.
Time complexity depends on array size because it checks each element.
Use ANY when you want to match any value; use ALL when you want to ensure all values meet the condition.
ANY checks if a value matches any element in an array.
ALL checks if a value matches all elements in an array.
These help compare one value against many easily in queries.