GROUP BY and HAVING in SQL

For Complete YouTube Video: Click Here

We will try to understand GROUP BY and HAVING in SQL in this class.

We have already discussed Nested queries in our previous class.

GROUP BY and HAVING in SQL

GROUP BY in SQL

The GROUP BY clause in a SQL command is to group rows with the same values.

The use of the GROUP BY clause is in the SELECT statement.

It is used with aggregate functions to produce summary reports from the database.

HAVING in SQL

Having is used to restrict the rows affected by the GROUP BY clause. It is similar to the WHERE clause.

Example Queries on GROUP BY & Having in SQL 

Query 1: Find the count of projects for each location.

To execute this query, we need the project table of the company database, as shown below.

GROUP BY and HAVING in SQL
GROUP BY and HAVING in SQL

We have to count the number of projects in each location from the above table.

For that to happen, we have to GROUP BY the plocation column of the project table.

The query and the output for the question are below.

GROUP BY and HAVING in SQL 1
GROUP BY and HAVING in SQL 1

Query 2: Find the project locations which have two projects.

The above question states a condition on query 1.

To restrict the number of rows of the output using GROUP BY, we must use HAVING.

The image below is the query and the output of the question.

GROUP BY and HAVING in SQL 2
GROUP BY and HAVING in SQL 2