Microsoft KB Archive/209066

= ACC2000: How to Create and Use Subqueries =

Article ID: 209066

Article Last Modified on 6/28/2004

-

APPLIES TO


 * Microsoft Access 2000 Standard Edition

-



This article was previously published under Q209066



Moderate: Requires basic macro, coding, and interoperability skills.

This article applies only to a Microsoft Access database (.mdb).



SUMMARY
Microsoft Access 2000 supports the use of subqueries. A subquery is a select query inside another select or action query that acts as a criterion for a field. A subquery can refer to a table that is part of the current query, or to a table that is not part of the current query. Union and crosstab queries are not supported as subqueries.

NOTE: You can see a demonstration of the technique that is used in this article in the sample file Qrysmp00.exe. For information about how to obtain this sample file, please see the following article in the Microsoft Knowledge Base:

207626 ACC2000: Access 2000 Sample Queries Available in Download Center



MORE INFORMATION
To create a subquery, type a valid SQL SELECT statement in the Criteria cell of the field whose value is being compared with the value selected in the subquery. The field that the criterion is specified for and the field that is being selected in the subquery must be of the same data type. You can also have a subquery in the Field row of the query grid, although it is not recommended.

A correlated subquery is one in which a column from a table specified in the FROM clause of the main query is used in the WHERE clause of the subquery, as demonstrated in the following example:

SELECT * FROM Table1 WHERE FirstName IN (SELECT FirstName FROM Table2 WHERE Table2.LastName=Table1.LastName);

Another way to tell if a subquery is a correlated subquery is if the subquery statement cannot be used by itself as a separate query. In the example above, Access would not be able to identify Table1.LastName if the second SELECT statement were used by itself in a separate query.

To create a subquery, follow these steps:

 Open the sample Northwind.mdb database. Create a new query, and then add the Products table. Add the ProductName and UnitPrice fields to the query grid. Create the subquery by typing the following SQL SELECT statement in the Criteria cell of the UnitPrice field:

<=(SELECT [UnitPrice] FROM [Products] WHERE [ProductName]= "Filo Mix")

 Run the query. Note that the query returns the products whose unit prices are less than or equal to the unit price for Filo Mix.

<div class="references_section">