Subqueries With ANY, SOME, and IN
Compare a value against any result from a subquery. The ANY (or SOME) operator returns TRUE if the comparison holds for at least one row. IN can be used for =ANY.
Syntax
SOME is a synonym for ANY. IN is a synonym for = ANY.
scalar_expression comparison_operator ANY <Table subquery>
scalar_expression comparison_operator SOME <Table subquery>
scalar_expression IN <Table subquery>scalar_expressionmay be any expression that evaluates to a single value.comparison_operatormay be any one of=,>,<,>=,<=,<>or!=.
ANY or SOME returns:
TRUEif the comparison operator returnsTRUEfor at least one row returned by the table subquery.FALSEif the comparison operator returnsFALSEfor all rows returned by the table subquery, or if the table subquery has no rows.NULLif the comparison operator returnsNULLfor at least one row returned by the table subquery and doesn't returnsTRUEfor any of them, or ifscalar_expressionreturnsNULL.
Examples
The subsequent examples use these tables:
CREATE TABLE sq1 (num1 TINYINT);
CREATE TABLE sq2 (num2 TINYINT);
INSERT INTO sq1 VALUES(100);
INSERT INTO sq2 VALUES(40),(50),(120);Subquery With ANY
ANY100 is greater than two of the three values, and so the expression evaluates to true.
Subquery With SOME
SOMESOME is a synonym for ANY.
100 is greater than two of the three values, and so the expression evaluates to true.
Subquery With IN
ININ is a synonym for = ANY.
The only value of 100 in sq1 is not in the list of values of sq2.
Adding a value to sq1 that matches one of the values in sq2 gives a match, though:
Since they're synonyms, =ALL returns the same result:
Subquery With NOT IN
NOT INAfter inserting 50 into sq1, the tables contain these values now:
sq1in thenum1column:50,100.sq2in thenum2column:40,50,120.
The value of 100 is not present in sq2.
The values of 40 and 120 are not present in sq1.
Subquery With NOT IN Versus <> ANY
NOT IN Versus <> ANYIN and =ANY are synonyms, but NOT IN and <>ANY aren't. Compare these queries:
The first query returns all values in sq2 that are not present in sq1.
The second query returns all values in sq2 unless they're only present in sq1 but not in sq2.
This page is licensed: CC BY-SA / Gnu FDL
Last updated
Was this helpful?

