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.

Chapter 6<br />

This section covers queries that provide more of a summary, or aggregation, of results. You learn how to<br />

use <strong>SQL</strong> to answer questions such as “How many members come from each state?” “What’s the average<br />

film rating of all the films in the Film Club database?” and “How old is the oldest person in the club?”<br />

The section begins by looking at the COUNT() aggregate function.<br />

Counting Results<br />

192<br />

You can use the COUNT() function to count the number of records in the results. It’s used in the SELECT<br />

statement along with the column list. Inside the brackets, insert the name of the column you want counted.<br />

The value returned in the results set is the number of non-NULL values in that column. Alternatively, you<br />

can insert an asterisk (*), in which case all columns for all records in the results set are counted regardless<br />

of whether the value is NULL or not. The COUNT() function can also accept expressions, for example<br />

COUNT(MemberId + CategoryId).<br />

Execute the following <strong>SQL</strong>:<br />

SELECT COUNT(*)<br />

FROM MemberDetails;<br />

You get the answer 14, which is how many records the <strong>SQL</strong> returns, which, given the lack of a WHERE<br />

clause, represents all the records in the MemberDetails table. However, if you execute the following <strong>SQL</strong>,<br />

you get the answer 13:<br />

SELECT COUNT(Street)<br />

FROM MemberDetails;<br />

Why 13 and not 14? After all, it’s the same <strong>SQL</strong> with no WHERE clause, so surely it has the same number<br />

of records regardless of which column is counted. The difference is that when a column name is specified<br />

in the COUNT() function’s arguments, only the columns where the value is not NULL are counted. As<br />

you can see from the following table, which is the result of SELECT MemberId, Street,City,State<br />

FROM MemberDetails, one of the records in the Street, City, and State columns contains a NULL value:<br />

MemberId Street City State<br />

1 Main Road Townsville Mega State<br />

4 45 Upper Road New Town New State<br />

5 Newish Lane Orange Town New State<br />

6 Newish Lane Orange Town New State<br />

7 Long Lane Orange Town New State<br />

8 Main Street Big City Mega State<br />

9 Long Lane Windy Village Golden State<br />

10 Main Road Townsville Mega State

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

Saved successfully!

Ooh no, something went wrong!