RelationalDBDesign
prev next prev next
  Course navigation
 
Lesson 4
Objective
GROUP BY vs. sorting in SQL
Create GROUP BY clause to sort
   
Create a GROUP BY clause to sort and group results from a query.
When you use the GROUP BY clause, you need to indicate which columns you are pulling from the table. These columns will be used by the engine to determine where the breaks in your groups will be.
If you are familiar with sorting, you might think of the GROUP BY clause as a sorting routine.
For example, suppose you have the following names to sort (i.e., alphabetize):
James
John
Jabernathy
Jinkies
Jobs
Because all the names begin with the letter "J," you alphabetize by comparing the second letter, then the third, and so on.
Working with the GROUP BY clause is much the same. When the engine considers your information, it will initially look at the first column. If the values are the same, the engine considers the second column, and so forth. Using this sorting routine, the SQL engine determines how to group the information.
One thing to remember about the GROUP BY clause is that you must include all columns taken from your table(s) in the clause. For example, the following statement is incorrect and will generate either an error or no results at all, depending on your engine:
SELECT * FROM Authors GROUP BY au_Lname
The reason is that you are selecting several different columns from the table, but only listing the single column as part of the GROUP BY clause. Since the engine may have to use the additional columns to resolve the sorting, it needs clear instructions about how to use those other columns.
Group By Clause Exercise
Complete this exercise about the GROUP BY clause by clicking the link below.
Group By Clause Exercise
Over the next several lessons the sub-SELECT statements will be examined.
  Course navigation