Description

The SQL provides the ANY and ALL operators to compare a single column value against a range of other values.

  • The operator ANY returns TRUE if any of the subquery values meet the condition.
  • The operator ALL returns TRUE if all of the subquery values meet the condition.
  • The comparison operator must be a standard comparison operator, like =, <, >, <=, >=, <>, !=, etc.,
  • These operators can be used only on SELECT statements, within the WHERE and HAVING clauses that define conditions.

Let's look at an example of a SELECT statement using ANY operator, to compare a column value against a set of other values from a subquery.

Table Data

Before executing any queries, consider the below data on the tables.

Customers Table Data

customer_id customer_name address city country postal_code
1 Maria Anders Obere Str. 57 Berlin Germany 12209
2 Fran Wilson C/ Araquil, 67 Madrid Spain 28023
3 Dominique Perrier 25, rue Lauriston Paris France 75016
4 Martin Blank Via Monte Bianco 34 Turin Italy 10100
5 Thomas Hardy 89 Chiaroscuro Rd. Portland USA 97219

Orders Table Data

order_id order_date order_value customer_id shipper_id
10250 2014-07-05 1807.5 1 3
10251 2014-07-15 1159 2 2
10252 2014-07-18 2822 3 3
10253 2014-07-19 2575.3 4 2
10254 2014-07-24 1256.25 5 3
10255 2014-07-31 9247.5 1 1

Example

The below SELECT statement returns the customers, having a customer ID that is equal to any of the customer IDs returned by the inner query.

  • The inner SELECT statement returns customer IDs from the orders table, having an order value of more than 2000. So, it returns the customers having ID values 1, 3, and 4.
  • The outer SELECT statement returns customers, having customer ID equal to any of the 1, 3, and 4. So, it returns all the three customers having those IDs.

Run this on IDE

SELECT *
FROM customers
WHERE customer_id = ANY (SELECT customer_id FROM orders WHERE order_value > 2000);

After successful execution, the output contains the below data.

customer_id customer_name address city country postal_code
1 Maria Anders Obere Str. 57 Berlin Germany 12209
3 Dominique Perrier 25, rue Lauriston Paris France 75016
4 Martin Blank Via Monte Bianco 34 Turin Italy 10100

Overall

We now know how to compare a single column value against a range of other values in a SELECT statement using ANY operator.

Related Links