Summary

Team-Fly    

 
Sams Teach Yourself SQL in 24 Hours, Third Edition
By Ronald R. Plew, Ryan K. Stephens
Table of Contents
Hour 14.  Using Subqueries to Define Unknown Data


By simple definition and general concept, a subquery is a query that is performed within another query to place further conditions on a query. A subquery can be used in a SQL statement's WHERE clause or HAVING clause. Queries are typically used within other queries (Data Query Language), but can also be used in the resolution of Data Manipulation Language statements such as INSERT, UPDATE, and DELETE. All basic rules for DML apply when using subqueries with DML commands.

The subquery's syntax is virtually the same as that of a standalone query, with a few minor restrictions. One of these restrictions is that the ORDER BY clause cannot be used within a subquery; a GROUP BY clause can be used, however, which renders virtually the same effect. Subqueries are used to place conditions that are not necessarily known for a query, providing more power and flexibility with SQL.

Q&A

Q1:

In the examples of subqueries, I noticed quite a bit of indentation. Is this necessary in the syntax of a subquery?

A1:

Absolutely not. The indentation is used merely to break the statement into separate parts , making the statement more readable and easier to follow.

Q2:

Is there a limit on the number of embedded subqueries that can be used in a single query?

A2:

Limitations such as the number of embedded subqueries allowed and the number of tables joined in a query are specific to each implementation. Some implementations may not have limits, although the use of too many embedded subqueries could drastically hinder SQL statement performance. Most limitations are affected by the actual hardware, CPU speed, and system memory available, although there are many other considerations.

Q3:

It seems that debugging a query with subqueries can prove to be very confusing, especially with embedded subqueries. What is the best way to debug a query with subqueries?

A3:

The best way to debug a query with subqueries is to evaluate the query in sections. First, evaluate the lowest -level subquery, and then work your way to the main query (the same way the database evaluates the query). When you evaluate each subquery individually, you can substitute the returned values for each subquery to check your main query's logic. An error with a subquery is often the use of the operator used to evaluate the subquery, such as (=), IN, >, <, and so on.


Team-Fly    
Top
 


Sams Teach Yourself SQL in 24 Hours
Sams Teach Yourself SQL in 24 Hours (5th Edition) (Sams Teach Yourself -- Hours)
ISBN: 0672335417
EAN: 2147483647
Year: 2002
Pages: 275

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net