
Any in PostgreSql
In PostgreSQL, ANY
is used in various ways, primarily in SQL queries and expressions. Here are some common use cases:
1. Using ANY
with IN
Alternative
ANY
works like IN
to check if a value matches any element in a list or subquery.
🔹 Example: Find users from a list of countries
SELECT * FROM users WHERE country = ANY (ARRAY['USA', 'Canada', 'India']);
(Same as WHERE country IN ('USA', 'Canada', 'India')
)
🔹 Using ANY
with a subquery:
SELECT * FROM users WHERE id = ANY (SELECT user_id FROM orders);
This checks if id
exists in the orders
table.
2. ANY
with Comparison Operators
You can use ANY
with comparison operators (>
, <
, =
) to compare against a list.
🔹 Find employees with a salary greater than any in a department:
SELECT * FROM employeesWHERE salary > ANY (SELECT salary FROM employees WHERE department = 'IT');
This checks if the salary is greater than at least one IT employee's salary.
🔹 Find products cheaper than any in a category:
SELECT * FROM productsWHERE price < ANY (SELECT price FROM products WHERE category = 'Electronics');
This returns products that are cheaper than at least one electronic product.
3. ANY
vs. ALL
ANY
means "at least one matches"ALL
means "must match all values"
🔹 Employees with a salary greater than all IT employees:
SELECT * FROM employeesWHERE salary > ALL (SELECT salary FROM employees WHERE department = 'IT');
(Finds employees earning more than every IT employee)
4. Using ANY
with Arrays
PostgreSQL supports array data types, and ANY
is useful for checking values inside arrays.
🔹 Find users who like any of these hobbies:
SELECT * FROM users WHERE 'Reading' = ANY(hobbies);
(hobbies
is an array column like TEXT[]
)
🔹 Check if any value exists in an array:
SELECT ARRAY[1, 2, 3] && ARRAY[2, 4, 6]; -- Returns TRUE (2 exists in both)
5. ANY
in JSONB Queries
If you have a jsonb
column, you can check if a value exists.
🔹 Example: Find users with any matching skill:
SELECT * FROM users WHERE skills ?| ARRAY['Go', 'Python', 'JavaScript'];
(Finds users whose skills
JSONB field contains any of the given values)
Summary
✅ ANY
is useful for:
- Checking if a value is in a list or subquery (
= ANY
) - Comparing against multiple values (
> ANY
,< ANY
) - Working with arrays (
ANY(array_column)
) - Querying JSONB fields (
?| ARRAY[...]
)