20.07.2013 Views

Beginning SQL

Beginning SQL

Beginning SQL

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 8<br />

In the query, the Category and Films tables are joined with an inner join based on CategoryId. The query<br />

then restricts which films form the results by use of a subquery in the WHERE clause. The subquery returns<br />

the lowest-priced DVD for a particular category. The category returned by the subquery is linked to the<br />

CategoryId of the Category table in the outer query. Note that Films.CategoryId inside the subquery<br />

refers to the Films table in that subquery, not to the Films table outside the subquery. Then in the WHERE<br />

clause of the outer query, Films.DVDPrice is compared with the minimum price for that category, which<br />

is returned by the subquery. If there’s a match, then clearly the film’s price matches the value of the minimum<br />

price.<br />

The results are as follows:<br />

Category FilmName DVDPrice<br />

Thriller The Maltese Poodle 2.99<br />

Romance On Golden Puddle 12.99<br />

Horror One Flew over the Crow’s Nest 8.95<br />

War Planet of the Japes 12.99<br />

Sci-fi Soylent Yellow 12.99<br />

Historical The Good, the Bad, and the Facially Challenged 8.95<br />

Now that you have a good handle on how subqueries function and how you can include them in<br />

SELECT lists and WHERE clauses, you can move on to more complex subqueries that employ various<br />

operators, including IN, ANY, SOME, and ALL.<br />

Operators in Subqueries<br />

So far, all the subqueries you’ve seen have been scalar subqueries — that is, queries that only return only<br />

one row. If more than one row is returned, you end up with an error. In this and the following sections,<br />

you learn about operators that allow you to make comparisons against a multirecord results set.<br />

Revisiting the IN Operator<br />

242<br />

You first learned about the IN operator in Chapter 3. Just to recap, the IN operator allows you to specify<br />

that you want to match one item from any of those in a list of items. For example, the following <strong>SQL</strong><br />

finds all the members who were born in 1967, 1992, or 1937:<br />

SELECT FirstName, LastName, YEAR(DateOfBirth)<br />

FROM MemberDetails<br />

WHERE YEAR(DateOfBirth) IN (1967, 1992, 1937);<br />

Note that this code, and any code that contains the YEAR() function, won’t work in Oracle because it<br />

doesn’t support the YEAR() function.

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

Saved successfully!

Ooh no, something went wrong!