When a SELECT statement is nested inside of a DELETE, INSERT, SELECT, SELECT INTO, or an UPDATE statement, it is referred to as a subquery clause.
There are three reserved words, ALL, ANY, and SOME, that can be used in subqueries to make comparisons. However, Microsoft states that ALL and SOME are synonymous.
SELECT * FROM MediCarePatients WHERE ssn IN
(SELECT ssn FROM DentalIns);
SSN
FullName
Address
City
State
PhoneNumber
123-45-6789
Jared Johnson
2020 Lakeview Dr.
Memphis
TN
(555) 555-5141
987-65-4321
Richard Danson
127 Leeland Heights
Chattanooga
TN
(555) 555-3124
111-22-3333
Tammy Harper
P.O. Box 5812
Powell
TN
(555) 555-2930
576-29-0012
Herbert Gaddis
P.O. Box 2281
Nashville
TN
(555) 555-0091
(4 row(s) affected)
In this example we create a table of Medicare patients who also have dental insurance. The social security number, ssn, is used as a key to compare the two tables, 'MediCarePatients' and 'DentalIns'.
SELECT * FROM MediCarePatients WHERE ssn NOT IN
(SELECT ssn FROM DentalIns);
SSN
FullName
Address
City
State
PhoneNumber
313-66-2001
Robert Davis
2812 Main St.
Cleveland
TN
(555) 555-0921
999-99-9999
Steven Raper
31 Belleview Rd.
Murfreesboro
TN
(555) 555-1812
488-48-8484
Jack Swanson
P.O. Box 3713
Nashville
TN
(555) 555-1276
(3 row(s) affected)
This query uses a NOT to create a table of Medicare patients who do not have dental insurance.
SELECT AvgEggSize FROM BillsBirdNestList WHERE AvgEggSize < ALL
(SELECT AvgEggSize FROM LindasBirdNestList);
AvgEggSize
1.5
2.0
2.3
(3 row(s) affected)
The "< ALL" comparison will create a list of AvgEggSize from BillsBirdNestList that contains only those entries that are smaller than the smallest AvgEggSize value in LindasBirdNestList.
SELECT AvgEggSize FROM BillsBirdNestList WHERE AvgEggSize < ANY
(SELECT AvgEggSize FROM LindasBirdNestList);
AvgEggSize
1.5
2.0
2.3
3.2
2.8
4.0
(6 row(s) affected)
In contrast to the "< ALL" comparison, the "< ANY" comparison will create a list of AvgEggSize from BillsBirdNestList that contains only those entries that are smaller than the largest AvgEggSize value in LindasBirdNestList.