GROUP BY Clause

The GROUP BY clause organizes the rows returned from a SELECT statement into groups. Within each group, you can apply an aggregate function, like count() or sum() to get the number of items or sum, respectively.

In this example, the SELECT query counts the number of rows for each category and groups the counts by category.

Categorycnt
Furniture2,121
Office Supplies6,026
Technology1,847

You can also group by multiple columns. This query generates the group of cities that contain stores in each category. The count column shows how many stores there are in each city.

Here are the first ten results.

CategoryCitycnt
FurnitureAkron2
 Alexandria3
 Allen1
 Allentown1
 Amarillo4
 Anaheim8
 Andover1
 Apopka1
 Apple Valley2

Grouping by ordinal number is not supported. You can’t refer to a results column or an expression created by input values by its index value. To shorten a lengthy expression in your query, use an alias. For example, this query throws an error.