You are on page 1of 3

Group By Clause

The GROUP BY statement groups rows that have the same values into
summary rows, like "find the sum of price of stock in each city".

The GROUP BY statement is often used with aggregate functions


(COUNT(), MAX(), MIN(), SUM(), AVG()) to group the result-set by one or
more columns.

GROUP BY Syntax
Select fieldname, aggregatefunction
From table name
Group by fieldname;
Note: fieldname mentioned in both places is same on which grouping is done.

How to decide when to use group by clause?


Observe the following example of table stock in which we have a price field.
If we want to find sum of price of all items in the table then we give
following command:

Select sum(price) from stock;


If we add a where clause in the above query it will again give me only one
result which satisfies the condition .
Eg select sum(price) from stock where address=’Mumbai’;
Shows sum of price of stocks from Mumbai only.

The deciding factor


If we want a report giving sum of stocks from each address(city) then we
need to group all common values from the column address and the
aggregate function will be then performed on the common grouped values
of that field.
Adding condition on group
If we want to place condition check on the group of values we will use
having clause.
Please note: where clause is NOT used on groups. It works on individual
rows.

Link for Video for reference

You might also like