Practical 7: Implement SQL queries using Group by, Having, order by clause
Group Functions:
Groupby, Having and Order by clause
1) SQL GROUP BY Clause
The SQL GROUP BY Clause is used along with the group functions to retrieve data
grouped according to one or more columns.
Syntax:
Select column1, column2……. columnN, Aggregate Function (argument) From
TableName Group By column1, column2……. columnN;
Example:
If you want to know the total amount of salary spent on each department, the query
would be:
Id Name Dept Age Salary Location
100 Ramesh Electrical 24 25000 Bangalore
101 Hrithik Electronics 28 35000 Bangalore
102 Harsha Aeronautics 28 35000 Mysore
103 Soumya Electronics 22 20000 Bangalore
104 Priya InfoTech 25 30000 Mangalore
Example:
SELECT dept, SUM (salary) FROM employee GROUP BY dept;
The output would be like:
Dept Salary
Electrical 25000
Electronics 55000
Aeronautics 35000
InfoTech 30000
2) SQL ORDER BY
The ORDER BY clause is used in a SELECT statement to sort results either in
ascending or descending order. Oracle sorts query results in ascending order by
default.
Syntax:
Select column1, column2……. columnN From TableName ORDER BY column1,
column2……. columnN;
Id Name Dept Age Salary Location
100 Ramesh Electrical 24 25000 Bangalore
101 Hrithik Electronics 28 35000 Bangalore
103 Soumya Electronics 22 20000 Bangalore
104 Priya InfoTech 25 30000 Mangalore
Example:
SELECT name, salary FROM employee ORDER BY salary;
The output would be like
Name Salary
Soumya 20000
Ramesh 25000
Priya 30000
Hrithik 35000
3) SQL HAVING Clause
Having clause is used to filter data based on the group functions. This is similar to
WHERE condition but is used with group functions.
Group functions cannot be used in WHERE Clause but can be used in HAVING
clause.
The HAVING clause must follow the GROUP BY clause in a query and must also
precedes the ORDER BY clause if used.
The following is the syntax of the SELECT statement, including the HAVING
clause:
Syntax:
SELECT column1, column2 FROM TableName WHERE [conditions] GROUP BY
column1, column2 HAVING [conditions];
Example:
SELECT dept, SUM (salary) FROM employee GROUP BY dept HAVING SUM
(salary) > 25000;