To use a subquery (SQ) in SQL there are two ways :
- Treating the SQ as a record source (like a table).
- Treating the SQ as a single value.
In either case, the SQ is a simple SELECT query but surrounded by parentheses ().
In case 1 the SQ should either be in the FROM clause or, sometimes possible put within the In() command.
In case 2 the SQ can be used in place of any other item that returns a value (SELECT; WHERE; HAVING; GROUP BY; etc).
Assume the following structure :
- Table Name=tblOKData
-
ID; Autonumber; PK
-
Name; String
with records :
- Table Name=tblALLData
-
ID; Autonumber; PK
-
Name; String
with records :
- 1 Glass
-
2 Cup
-
3 Plate
-
21 Bat
-
22 Ball
-
23 Racquet
Using a SQ within In().
Say that we wanted to show the tblAllData.ID for all items whose names match those found in the tblOKData table. We could use an INNER JOIN in this case, but alternatively (necessary to illustrate the point here) we could do it with a SQ.
The code would be :
- SELECT ID
-
FROM tblAllData
-
WHERE Name In(SELECT [Name]
-
FROM tblOKData)
Using a SQ within the FROM clause as a Recordset.
The simplest form of this is to surround a basic SELECT query in parentheses and rename (AS {Name}).
In this case we want the same effect as the SQL above.
The code would be :
- SELECT subQ.ID
-
FROM (SELECT *
-
FROM tblAllData) AS subQ INNER JOIN tblOKData
-
ON subQ.Name = tblOKData.Name
Using a SQ as a Simple Value.
We want to select all tblAllData.IDs which are greater than the average value of these IDs.
The code would be :
- SELECT [ID]
-
FROM tblAllData
-
WHERE [ID]>(SELECT Avg([ID])
-
FROM tblAllData)