Sql Server SOME ANY ALL keywords
- Posted by Sqltimes
- On December 6, 2013
- 0 Comments
Something interesting I ran into a few days ago, were these new keywords (new to me) in Sql Server.
- SOME
- ANY
- ALL
ALL is used several places so, its not all too new (ex: REBUILD INDEXES, GRANT ALL, etc), but SOME and ANY are particularly new and interesting. What is the purpose? Could it not be done using IN clause?
Talking just about the intent of these clauses, SOME says that ‘return any matching records from parent query, where it matches with some of the result set from the subquery‘. It works in TRUE or FALSE logic. The left hand side (LHS) of SOME logic looks at the scalar list on the right hand side and says if the values in the LHS have matching with some of the scalars values on the RHS. Some is the key here, if there is a match, it returns TRUE orelse FALSE.
Similarly ANY and ALL have similar logic. ANY says, if there is even one match then returns TRUE. ALL needs it to match with all the scalar values. One other requirement is that for SOME/ANY the RHS needs to be a subquery.
There are some situations, we can replace SOME/ANY with IN clause. But there are situations where having SOME/ANY are more appropriate. Also, with SOME/ANY we can use more logical operators =, <, >, <>, etc than with IN clause.
Some Examples:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
|
-- -- Example for SOME - Returns TRUE -- IF 3 > SOME ( SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 ) PRINT 'TRUE' ELSE PRINT 'FALSE' ; -- -- Example for ALL - Returns FALSE -- IF 3 > ALL ( SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 ) PRINT 'TRUE' ELSE PRINT 'FALSE' ; -- -- Example for ANY - Returns TRUE -- IF 3 < ANY ( SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 ) PRINT 'TRUE' ELSE PRINT 'FALSE' ; |
Example, where using IN clause makes more sense than using SOME. As you can see below, the execution plan is not very different either way. But keep in mind that actual execution plan for your data set might vary (execution plan below is based on a small data set). Let’s say you want to retrieve records that match with a list of scalar values:
1
2
3
4
5
6
7
|
SELECT * FROM dbo. Table WHERE ID IN ( SELECT ID FROM dbo.AR_Account WHERE CustomerPK IN (2, 5) ) |
This could be written using SOME like this:
1
2
3
4
5
6
7
|
SELECT * FROM dbo. Table WHERE ID = SOME ( SELECT ID FROM dbo.AR_Account WHERE CustomerPK IN (2, 5) ) |
Execution Plan:
Hope this helps,
_Sqltimes
0 Comments