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.

Returning Only Distinct Rows<br />

If you want to know all the unique values in a record, how would you go about retrieving them? The<br />

answer is by using the DISTINCT keyword. The DISTINCT keyword is added to the SELECT statement’s<br />

column listing, directly after the SELECT keyword. For example, if someone asks you which cities members<br />

come from, you could try a query similar to the following:<br />

SELECT City FROM MemberDetails;<br />

Executing the query gives you the following results:<br />

City<br />

Townsville<br />

Orange Town<br />

New Town<br />

Orange Town<br />

Orange Town<br />

Big City<br />

Windy Village<br />

As you can see, Orange Town is listed three times because there are three members from that city. But if<br />

you simply want a list of the unique places that members live in, you could add the DISTINCT keyword:<br />

SELECT DISTINCT City FROM MemberDetails;<br />

Executing the modified query gives these results:<br />

City<br />

Big City<br />

New Town<br />

Orange Town<br />

Townsville<br />

Windy Village<br />

This time, Orange Town is mentioned just once. The DISTINCT keyword works on all columns in combination;<br />

all the columns listed in the SELECT statement must be unique. If you change the previous query<br />

to include MemberId, which is unique for every single row, and rerun the query, you end up with all<br />

the rows:<br />

SELECT DISTINCT City, MemberId FROM MemberDetails;<br />

Extracting Information<br />

55

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

Saved successfully!

Ooh no, something went wrong!