Subqueries in SQL

Visited 1110 times | Submited on 2007-06-05 08:57:31

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 :

  1. Table Name=tblOKData
  2. ID; Autonumber; PK
  3. Name; String

with records :
  1. 1   Bat
  2. 2   Ball
  3. 3   Racquet
  1. Table Name=tblALLData
  2. ID; Autonumber; PK
  3. Name; String
with records :
  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 :
  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 :
  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 :
  1. SELECT [ID]
  2. FROM tblAllData
  3. WHERE [ID]>(SELECT Avg([ID])
  4.             FROM tblAllData)
Source: thescripts.com


Add your comment

Name:(required)
E-mail address:(optional)
Comment:(required)
Repeat the number for validation: (required)

Browse by Tags:


Related Articles:

Text Link Ads

Statistics

Total 296 articles submitted
Latest submission at January 28, 2008 15:13

Feedback

Use this email below to send us your suggestions and feedback. We value your opinion.
info (at) theitarticles.com