Group By-Having-Join
Group By-Having-Join
The GROUP BY clause groups a set of records that have identical values into a set of summary
records according to specified condition/expression. It is used with SELECT statement.
Grouping of records can be done by a column name along with aggregate functions.
Example: Count the no of GRADES with grouping.
select GRADE, COUNT(*) from STUDENT_MARK GROUP BY GRADE;
Example: Display Maximum marks Branch wise.
select BRANCH, MAX(TOTAL_MARKS) as MAX_MARKS from STUDENT_MARK GROUP BY
BRANCH;
Example: Display the average mark Branch wise.
select BRANCH, AVG(TOTAL_MARKS) as AVG_MARKS from STUDENT_MARK GROUP BY BRANCH;
Placing condition on GROUP BY clause – Use of HAVING clause
The HAVING clause is often used with the GROUP BY clause to filter groups based on a specified
condition. It is similar to WHERE clause but WHERE cannot be used with GROUP BY.
Example: Display those branches whose students have secured average mark more than 700.
select BRANCH, AVG(TOTAL_MARKS) as AVG_MARKS from STUDENT_MARK GROUP BY BRANCH
HAVING AVG(TOTAL_MARKS)>=700;
Displaying Data from multiple tables – Table Joins (Important)
Sometimes, in real-time applications, it is required to display records from more than one tables
by using a single SELECT command/statement. This can be possible by using join operation.
Join is an SQL operation that combines rows/records from two or more tables. An SQL join-
query is used with SELECT command where more than one table are listed in the FROM clause.
For example:
Select * from Employee, Department;
The above statement is a type of sql join-query. When it is executed, it will display all records
from Employee table and Department table.
Cross Join
Cross Join (also called Cartesian Product) operation of two tables produces another table as the
output by pairing up each row of first table with each row of second table.
In this operation, if one table contains ‘m’ no. of rows and the other table contains ‘n’ no. of rows
then their cartesian product will contain m x n rows.
Let’s consider the following tables – Customer and C_Order
Customer C_Order
Retrieve Customer Name, Balance Due, Contact No, Order name and Order Date.
18
Here, Cross Join/Cartesian Product operation will be applied on two tables to get the desired
result.
Customer table contains 3 rows and C_Order table contains 3 rows. The resultant table will
contain 3 x 3 = 9 rows.
Select C_Name, Bal_Due, Contact_No, O_Name, O_Date from Customer, C_Order;
OUTPUT
19
Features of Natural Join
1. It will perform the Cartesian product (but not pure Cartesian product).
2. It finds consistent tuples and deletes inconsistent tuples.
3. Then it deletes the duplicate attributes.
Let’s consider an example.
EMPLOYEE
DEPARTMENT
20