Hello folks! In the series of SQL with JournalDev, today, we will be having a look at an important topic of discussion — SQL Having v/s Group By clause, in detail.
So, let us begin!!
Let us talk about the MySQL Group By and Having clause now!
Before moving ahead with the differences between SQL Having and Group By clause, let us first ponder over the understanding of these clauses in SQL.
In SQL, the Group By clause is used to represent data from various columns assembled and presented as a group. By this, we can club the data from various columns against a specific data column of the table.
Having understood these Clauses, let us have a look at the below example to have a clear picture about Having and Group By clause.
create table Info(Roll integer, Marks integer, Division varchar(200)); insert into Info(Roll, Marks, Division) values(2, 32,'B'); insert into Info(Roll, Marks, Division) values(3, 10,'A'); insert into Info(Roll, Marks, Division) values(5, 1,'C'); insert into Info(Roll, Marks, Division) values(4, 100,'B');
select SUM(Marks),Division from Info Group BY Division HAVING SUM(Marks)>30;
Here, I have clubbed Group By with the Having clause. I have selected the SUM of marks and grouped it by Division column such that it represents only those values whose Division has the sum of marks greater than 30.
SQL Having Clause v/s Group By — Get set GO!
Now that you have a brief idea about the Having and Group By clauses, let’s discuss the differences between these two SQL clauses.
So, with out any further delay, let us begin!! 🙂
|SQL HAVING||SQL GROUP BY|
|The HAVING clause enables us to restrict the output values by applying certain conditions. Only those values that satisfy the condition are printed as a result of the query||The Group By clause enables us to group and represent the data according to a specific category or column type.|
|Having clause does contain the SQL Aggregate functions which enables us to add conditions on the data values||SQL Group By clause does not make use of aggregate functions as it deals only with the grouping of values around a specific category.|
|SQL Having clause cannot be used without a Group By clause||But we can definitely use a Group By clause in the absence of a Having Clause. That is, we do not require a group By clause to be used alongside a Having clause.|
By this, we have come to the end of this article. Feel free to comment below, incase you come across any question. Try implementing SQL Having clause and Group By clause against various examples and do let us know your experience in the comment section.
For more such posts related to SQL, stay tuned!
Till then, Happy Learning!! 🙂