RelationalDBDesign
RedhatLinuxSys Seomining
prev next prev next
Course navigation
Lesson 3 GROUP BY Clause in SQL
Objective An example of the GROUP BY clause
Suppose you issue a simple SELECT statement against the PUBS database:
SELECT State FROM Authors
The result is 23 rows of states, ranging from California (15 instances) to Utah (2 instances).
Each of the other states represented appears once.
Suppose you wanted to show the count of each state in the table.
This is where grouping comes in.
If you can group by state, then count the states returned, correct?
That is exactly what you will do.
Here is the statement that will do the trick:
SELECT State, count(State) 
FROM Authors 
GROUP BY State
Two things are happening here.
  1. First, you indicate the column (State) and table (Authors) that you want to use.
  2. By using the COUNT function, SQL will return the count of all rows returned for that column.
    By adding the GROUP BY clause, SQL will condense the rows that have the same state, eliminating duplicates:
The grouping of states
Note that the second column has no heading. This is because the column is calculated on the fly, without specifying a column heading. Your application may label the column with NULL, No Column Heading, or some other indication that the column heading was not provided.
Course navigation