20.07.2013 Views

Beginning SQL

Beginning SQL

Beginning SQL

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

8<br />

Queries within Queries<br />

This chapter examines how you can nest one query inside another. <strong>SQL</strong> allows queries within<br />

queries, or subqueries, which are SELECT statements inside SELECT statements. This might sound<br />

a bit odd, but subqueries can actually be very useful. The downside, however, is that they can<br />

consume a lot of processing, disk, and memory resources.<br />

A subquery’s syntax is just the same as a normal SELECT query’s syntax. As with a normal SELECT<br />

statement, a subquery can contain joins, WHERE clauses, HAVING clauses, and GROUP BY clauses.<br />

Specifically, this chapter shows you how to use subqueries with SELECT statements, either returning<br />

results inside a column list or helping filter results when used inside a WHERE or HAVING<br />

clause; to update and delete data by using subqueries with UPDATE and DELETE statements; and<br />

with operators such as EXISTS, ANY, SOME, and ALL, which are introduced later in this chapter.<br />

Subqueries are particularly powerful when coupled with <strong>SQL</strong> operators such as IN, ANY, SOME,<br />

and ALL, which are covered shortly. However, the chapter begins with a few easy examples of<br />

subqueries. Before starting, you should note that versions of My<strong>SQL</strong> prior to version 4.1 do not<br />

fully support subqueries and many of the examples in this chapter won’t work on early versions<br />

of My<strong>SQL</strong>.<br />

Subquery Terminology<br />

Throughout this chapter, you’ll notice references to the outer and inner subqueries. The outer<br />

query is the main SELECT statement, and you could say that so far all of your SELECT statements<br />

have been outer queries. Shown below is a standard query:<br />

SELECT MemberId FROM Members;<br />

Using the standard query, you can nest — that is, place inside the outer query — a subquery, which<br />

is termed the inner query:<br />

SELECT MemberId FROM MemberDetails<br />

WHERE MemberId = (SELECT MAX(FilmId) FROM Films);

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!