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.

Now NOT EXISTS returns true, and as a result the WHERE clause is also true. The final results are<br />

shown in the following table:<br />

City<br />

Orange Town<br />

Windy Village<br />

Big City<br />

These examples are very simple and, to be honest, not that realistic in terms of how EXISTS is used. One<br />

issue with the examples is that the subqueries don’t link in any way with the outer SELECT query,<br />

whereas normally you’d expect them to do so. The following Try It Out example is a lot more realistic.<br />

The task is to find out which categories have been chosen by three or more members as their favorite category<br />

of film, but these favorite categories must contain at least one film with a rating higher than 3.<br />

Try It Out Using the EXISTS Operator<br />

Build the necessary query by following these steps:<br />

1. First of all, formulate a SELECT statement that returns the values you want. In this case, you just<br />

want the Category from the Category table:<br />

SELECT Category<br />

FROM Category<br />

2. Now you need to add a WHERE clause to ensure that you get only categories that have films<br />

rated 4 or higher and that have also been selected as a favorite by three or more members.<br />

SELECT Category<br />

FROM Category<br />

WHERE EXISTS (SELECT * FROM Films<br />

WHERE Category.CategoryId = Films.CategoryId<br />

AND Rating > 3<br />

)<br />

Queries within Queries<br />

3. Finally, you just want categories that three or more members have chosen as their favorite.<br />

SELECT Category<br />

FROM Category<br />

WHERE EXISTS (SELECT * FROM Films<br />

WHERE Category.CategoryId = Films.CategoryId<br />

AND Rating > 3<br />

AND (SELECT COUNT(CategoryId)<br />

FROM FavCategory<br />

WHERE FavCategory.CategoryId = Category.CategoryId)<br />

>= 3<br />

);<br />

251

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

Saved successfully!

Ooh no, something went wrong!