SQL GROUP BY Statement

« Previous Chapter Next Chapter »

Aggregate functions often need an added GROUP BY statement.

The GROUP BY Statement

The GROUP BY statement is used in conjunction with the aggregate functions to group the result-set by one or more columns.

SQL GROUP BY Syntax

SELECT column_name, aggregate_function(column_name)
FROM table_name
WHERE column_name operator value
GROUP BY column_name


SQL GROUP BY Example

We have the following "Purchases" table:

PU_ID OrderDate OrderPrice Customer
1 2015/11/12 1000 Karmen
2 2015/10/23 1600 Tendulkar
3 2015/09/02 700 Karmen
4 2015/09/03 300 Karmen
5 2015/08/30 2000 Jensen
6 2015/10/04 100 Tendulkar

Now we want to find the total sum (total order) of each customer.

We will have to use the GROUP BY statement to group the customers.

We use the following SQL statement:

SELECT Customer,SUM(OrderPrice) FROM Purchases
GROUP BY Customer

The result-set will look like this:

Customer SUM(OrderPrice)
Karmen 2000
Tendulkar 1700
Jensen 2000

Nice! Isn't it? :)

Let's see what happens if we omit the GROUP BY statement:

SELECT Customer,SUM(OrderPrice) FROM Purchases

The result-set will look like this:

Customer SUM(OrderPrice)
Karmen 5700
Tendulkar 5700
Karmen 5700
Karmen 5700
Jensen 5700
Tendulkar 5700

The result-set above is not what we wanted.

Explanation of why the above SELECT statement cannot be used: The SELECT statement above has two columns specified (Customer and SUM(OrderPrice). The "SUM(OrderPrice)" returns a single value (that is the total sum of the "OrderPrice" column), while "Customer" returns 6 values (one value for each row in the "Purchases" table). This will therefore not give us the correct result. However, you have seen that the GROUP BY statement solves this problem.

GROUP BY More Than One Column

We can also use the GROUP BY statement on more than one column, like this:

SELECT Customer,OrderDate,SUM(OrderPrice) FROM Purchases
GROUP BY Customer,OrderDate

« Previous Chapter Next Chapter »

Have Any Suggestion? We Are Waiting To Hear from YOU!

Your Query was successfully sent!