The Wayback Machine - https://web.archive.org/web/20240707135406/https://www.geeksforgeeks.org/sql-server-universal-comparison-quantified-predicates-any-all-some/
Open In App

SQL Server Universal Comparison Quantified Predicates (ANY, ALL, SOME)

Last Updated : 11 Oct, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Quantified Comparison Predicates are used to compare the value with every value in the set returned by the subquery. There are mainly two predicates available in SQL Server that are ALL and ANY/SOME.

This clause is very useful when you have to compare two sets of values. These clauses are used for broader comparison just like OR and AND. Like, for ANY you can think of it as a combination of OR clauses in which you are comparing the value with all the values of the Subquery. While ALL is simpler for shortening the expression with an AND clause between the two comparisons.

Example: If you want to compare one value with a set of values, you can use the OR/AND operator for conjunction like this

price=100 OR price=200 OR price=300

But, what if these values are not static and are coming from the table OR would be a waste of our efforts and thus ANY and ALL comes into the play?

Before jumping to the explanation of the clause, let’s prepare the database that we can use for practice in this article.

Let’s have a table of Products shown below:

Query for Creation of database

CREATE TABLE Products (
ProductID INT PRIMARY KEY,
ProductName VARCHAR(255),
UnitPrice DECIMAL(10, 2),
CategoryID INT
);

Inserting the Records in Products Table.

-- Insert sample data into the Products table

INSERT INTO Products (ProductID, ProductName, UnitPrice, CategoryID)
VALUES (1, 'Laptop', 1200.00, 1);

INSERT INTO Products (ProductID, ProductName, UnitPrice, CategoryID)
VALUES (2, 'Smartphone', 800.00, 1);

INSERT INTO Products (ProductID, ProductName, UnitPrice, CategoryID)
VALUES (3, 'Headphones', 100.00, 2);

INSERT INTO Products (ProductID, ProductName, UnitPrice, CategoryID)
VALUES (4, 'Monitor', 500.00, 1);

INSERT INTO Products (ProductID, ProductName, UnitPrice, CategoryID)
VALUES (5, 'Keyboard', 50.00, 1);

INSERT INTO Products (ProductID, ProductName, UnitPrice, CategoryID)
VALUES (6, 'Mouse', 20.00, 1);

INSERT INTO Products (ProductID, ProductName, UnitPrice, CategoryID)
VALUES (7, 'Tablet', 300.00, 1);

INSERT INTO Products (ProductID, ProductName, UnitPrice, CategoryID)
VALUES (8, 'Printer', 150.00, 3);

INSERT INTO Products (ProductID, ProductName, UnitPrice, CategoryID)
VALUES (9, 'External Hard Drive', 80.00, 3);

INSERT INTO Products (ProductID, ProductName, UnitPrice, CategoryID)
VALUES (10, 'Graphics Card', 350.00, 4);

INSERT INTO Products (ProductID, ProductName, UnitPrice, CategoryID)
VALUES (11, 'RAM', 70.00, 4);

INSERT INTO Products (ProductID, ProductName, UnitPrice, CategoryID)
VALUES (12, 'SSD Drive', 100.00, 4);

INSERT INTO Products (ProductID, ProductName, UnitPrice, CategoryID)
VALUES (13, 'Camera', 400.00, 5);

INSERT INTO Products (ProductID, ProductName, UnitPrice, CategoryID)
VALUES (14, 'TV', 600.00, 5);

INSERT INTO Products (ProductID, ProductName, UnitPrice, CategoryID)
VALUES (15, 'Speakers', 80.00, 5);
Product Table

Product Table

ALL

ALL is used with the WHERE clause and it returns TRUE or FALSE according to the results. Syntax of ALL clause is given below

scalar_expression ALL (subquery )

Now, let’s consider a case where you want to Find products in each category that are cheaper than ALL other products in the same category.

SELECT ProductName
FROM Products p
WHERE UnitPrice <
ALL (SELECT UnitPrice FROM Products WHERE CategoryID = p.CategoryID AND ProductID <> p.ProductID);

Explanation of the Query:

1. Subquery will return the UnitPrice of all the products that are from the same Category but the ProductID is different. So for the Mouse which has an Id = 6, Subquery will return every record’s unit price which has the same Category except Id 6.

Output of the Subquery

Output of the SubQuery

2. Now this set of records is being compared with the 20. And if it is less than from Every value of the set then it will return TRUE in WHERE statement which means it will be printed in output.

So, the result of the query is shown below.

Final Output

Final Output

ANY/SOME

ANY and SOME are the synonyms and can be used interchangeably. So, ANY is similar to ALL. Only the difference is it will compare only till the first comparison where it can get the output TRUE. So, ANY stats that I will compare the value and returns true if I find ANY comparison as TRUE, and if I don’t get any one from them then I will return FALSE.

Let’s explore this with a problem: Find products that are priced greater than ANY product in a different category.

The query for this will be very similar to the above one.

SELECT ProductName
FROM Products p
WHERE UnitPrice > ANY (SELECT UnitPrice FROM Products WHERE CategoryID <> p.CategoryID);

Explanation of the Query

1. Subquery will return the UnitPrice of all the products that are not from the same Category. So for the Laptop which is having a CategoryID = 1, Subquery will return all records of CategoryID other than 1.

output

output

2. Now this set of records is being compared with the 100. And if it is more than ANY value of the set then it will return TRUE in WHERE statement which means it will be printed in output.

So, the Final Result of the query is as follows:

Final Result

Final Result

Conclusion

So now we have the idea regarding this predicates about the definition and there uses. Talking about the real-time use of such predicates are generally with Stored Procedure. Thus, it would take less execution time.

Some cases where such predicates are used widely and you can practice such situations:

  1. Analyzing courses to find those with enrollments higher than any or all other courses in a specific category.
  2. Comparing user ratings to find products with ratings higher or lower than the average rating of products in a specific category.
  3. Identifying stocks that are trading at prices higher or lower than any or all other stocks in a particular sector.
  4. Analyzing sales data from two different time periods and identifying products with sales higher or lower than any or all products in the previous period.


Similar Reads

SQL Server ANY Operator
In SQL Server there are many different types of Logical operators like ANY, AND, LIKE, EXISTS, NOT, IN, and BETWEEN. The logical operators are used to perform conditional checks in SQL Queries. These operators are very useful to filter and compare single or multiple data in SQL Queries. In this article let us discuss the 'ANY' operator available in
3 min read
Dynamic SQL in SQL Server
In SQL Server, at times the SQL Queries need to be dynamic and not static, meaning the complete SQL query may be built dynamically at run time as a string using the user inputs and any specific application logic. This can be done in queries run from back-end applications or inside stored procedures. In this article let us look into the details abou
6 min read
Dynamic SQL and Temporary Tables in SQL Server
In SQL Server, creating and using Temp Tables using dynamic SQL is a good feature when we need to temporarily create tables at run time and delete automatically all within a session. They can be very useful when we need to store temporary data in a structured format and do data manipulation using Data Manipulation Language in SQL. In this article l
6 min read
BULK INSERT in SQL Server(T-SQL command)
BULK INSERT in SQL Server(T-SQL command): In this article, we will cover bulk insert data from csv file using the T-SQL command in the SQL server and the way it is more useful and more convenient to perform such kind of operations. Let's discuss it one by one.  ConditionSometimes there is a scenario when we have to perform bulk insert data from .cs
3 min read
Universal Language Model Fine-tuning (ULMFit) in NLP
In this article, We will understand the Universal Language Model Fine-tuning (ULMFit) and its applications in the real-world scenario. This article will give a brief idea about ULMFit working and the concept behind it. What is ULMFit?ULMFit, short for Universal Language Model Fine-tuning, is a revolutionary approach in natural language processing (
9 min read
SQL vs NO SQL vs NEW SQL
SQL stands for Structured Query Language. Which is based on relational algebra and schema is fixed in this which means data is stored in the form of columns and tables. SQL follows ACID properties which means Atomicity, Consistency, Isolation, and Durability are maintained. There are three types of languages present in SQL : Data Definition Languag
2 min read
SQL Server ALL Operator
In SQL Server the logical operators are used to perform conditional checks in SQL Queries. There are many different types of Logical operators like ANY, AND, LIKE, EXISTS, NOT, IN, and BETWEEN in SQL Server. These operators are very useful to filter and compare single or multiple data in SQL Queries. In this article let us discuss the 'ALL' operato
3 min read
Union and Union All in MS SQL Server
In MS SQL Server, the UNION and UNION ALL operators are used to combine the result sets of two or more SELECT statements into a single result set. This allows you to retrieve data from multiple tables or views and combine it into a single dataset. The primary difference between UNION and UNION ALL is that UNION removes duplicate rows from the resul
2 min read
SQL | ALL and ANY
ALL &amp; ANY are logical operators in SQL. They return boolean value as a result. ALL ALL operator is used to select all tuples of SELECT STATEMENT. It is also used to compare a value to every value in another value set or result from a subquery. The ALL operator returns TRUE if all of the subqueries values meet the condition. The ALL must be prec
2 min read
Differences Between Selenium Standalone server and Selenium Client and WebDriver Server
In web application testing, Selenium has emerged as one of the most basic foundations, providing robust mechanisms for automating browsers. Among its suite, two elements stand out, which are: 'Selenium-server-standalone.jar' and 'Selenium Client and WebDriver'. Both 'Selenium-server-standalone.jar' and 'Selenium Client and WebDriver' are very impor
4 min read