Subqueries (Cont.)


Many times, there are more than one SQL statement able to answer the question.

Question IX (Multiple Forms)
Retrieve all information concerning agents based in Duluth or Dallas.    
agent
aid aname city percent
a01 Smith New York 6
a02 Jones Newark 6
a03 Brown Tokyo 7
a04 Gray New York 6
a05 Otasi Duluth 5
a06 Smith Dallas 5


aid
a05
a06
The most local scope rule is applied to the name definition. For example, both tables customer and agent include a column city. The city belongs to the table agent according to the most local scope rule in the following SQL statement (the CAP database).
Question X (The Most Local Scope Rule)
Determine the names and discounts of all customers who place orders through agents in Duluth or Dallas.  
cname discnt
TipTop 10
Basics 12
ACME 8
ACME 0
The outer SELECT can provide data to an inner subquery. When a subquery involves a single table, it does not require a qualified reference to a column name.

Question XI (A Qualified Reference for Subqueries)
Find the names of customers who order product p05.    
cname
Allied
TipTop


Demonstration
Below is an SQL test area from W3Schools, which uses the well-known Northwind sample database. The tables here are for read only because of the problem of embedding the scripts. For a fully working example, check this by using Chrome.

SQL Statement:

Edit the SQL statement and click     to see the result, or  

Result:
The Database includes:
The Database includes:

TablenameRecord
Customers91
Categories8
Employees10
OrderDetails518
Orders196
Products77
Shippers3
Suppliers29