Subqueries in SQL

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • NeoPa
    Recognized Expert Moderator MVP
    • Oct 2006
    • 32661

    Subqueries in SQL

    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 :
    Code:
    [b]Table Name=tblOKData[/b]
    ID; Autonumber; PK
    Name; String
    with records :
    Code:
    1   Bat
    2   Ball
    3   Racquet
    Code:
    [b]Table Name=tblALLData[/b]
    ID; Autonumber; PK
    Name; String
    with records :
    Code:
    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 :
    Code:
    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 :
    Code:
    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 :
    Code:
    SELECT [ID]
    FROM tblAllData
    WHERE [ID]>(SELECT Avg([ID])
                FROM tblAllData)
    Attached Files
Working...