By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,190 Members | 777 Online
Bytes IT Community
Submit an Article
Got Smarts?
Share your bits of IT knowledge by writing an article on Bytes.

Subqueries in SQL

NeoPa
Expert Mod 15k+
P: 31,660
To use a subquery (SQ) in SQL there are two ways :
  1. Treating the SQ as a record source (like a table).
  2. 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 :
Expand|Select|Wrap|Line Numbers
  1. Table Name=tblOKData
  2. ID; Autonumber; PK
  3. Name; String
with records :
Expand|Select|Wrap|Line Numbers
  1. 1   Bat
  2. 2   Ball
  3. 3   Racquet
Expand|Select|Wrap|Line Numbers
  1. Table Name=tblALLData
  2. ID; Autonumber; PK
  3. Name; String
with records :
Expand|Select|Wrap|Line Numbers
  1. 1   Glass
  2. 2   Cup
  3. 3   Plate
  4. 21  Bat
  5. 22  Ball
  6. 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 :
Expand|Select|Wrap|Line Numbers
  1. SELECT ID
  2. FROM tblAllData
  3. WHERE Name In(SELECT [Name]
  4.               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 :
Expand|Select|Wrap|Line Numbers
  1. SELECT subQ.ID
  2. FROM (SELECT *
  3.       FROM tblAllData) AS subQ INNER JOIN tblOKData
  4.   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 :
Expand|Select|Wrap|Line Numbers
  1. SELECT [ID]
  2. FROM tblAllData
  3. WHERE [ID]>(SELECT Avg([ID])
  4.             FROM tblAllData)
Attached Files
File Type: zip SubQueries.Zip (8.6 KB, 666 views)
Jan 26 '07 #1
Share this Article
Share on Google+