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.

Appendix A<br />

WHERE (SELECT COUNT(*) from MemberDetails MD2<br />

WHERE NOT EXISTS (SELECT * FROM Location L1 WHERE L1.City = MD2.City AND L1.State =<br />

MD2.State)<br />

AND MD1.City = MD2.City AND MD1.State = MD2.State<br />

GROUP BY City, State) >= 2<br />

The final query gives the following results:<br />

City State<br />

Townsville Mega State<br />

Chapter 9<br />

Exercise 1 Solution<br />

386<br />

The easiest and safest way to delete data is first to write a SELECT query that selects the data you want<br />

to delete and then to change the SELECT statement to a DELETE statement.<br />

Begin with the SELECT column list and FROM clause:<br />

SELECT StarId, StarName, StarAge FROM FilmStars S1;<br />

This query simply returns all rows and columns from the table. The table has a primary key and the<br />

StarId column, and luckily enough, the values entered there are unique. However, the star’s name<br />

should be unique, but it isn’t. Therefore, you need to search for instances where there are duplicate<br />

names but where the StarId is different. To do this, you can use an IN operator and a subquery that simply<br />

returns all rows:<br />

SELECT StarId, StarName, StarAge FROM FilmStars S1<br />

WHERE StarName IN (SELECT StarName FROM FilmStars);<br />

If you run this query, you get the following results:<br />

StarId StarName StarAge<br />

1 Boris Carlot 102<br />

1 Scarlet O’Hairpin 89<br />

3 Boris Carlot 102<br />

4 Michael Hourglass 56<br />

5 Dusty Hoffperson 48<br />

6 Boris Carlot 102<br />

7 Dusty Hoffperson 48

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

Saved successfully!

Ooh no, something went wrong!