SQL Lesson 11 - Queries with aggregates (Pt. 2)

Our queries are getting fairly complex, but we have nearly introduced all the important parts of a SELECT query. One thing that you might have noticed is that if the GROUP BY clause is executed after the WHERE clause (which filters the rows which are to be grouped), then how exactly do we filter the grouped rows?

Luckily, SQL allows us to do this by adding an additional HAVING clause which is used specifically with the GROUP BY clause to allow us to filter grouped rows from the result set.

Select query with HAVING constraint

SELECT group_by_column, AGG_FUNC(_column_expression_) AS aggregate_result_alias, … FROM mytable WHERE _condition_ GROUP BY column **HAVING _group_condition_**;

The HAVING clause constraints are written the same way as the WHERE clause constraints, and are applied to the grouped rows. With our examples, this might not seem like a particularly useful construct, but if you imagine data with millions of rows with different properties, being able to apply additional constraints is often necessary to quickly make sense of the data.

Did you know?

If you aren't using the GROUP BY clause, a simple WHERE clause will suffice.

Exercise

For this exercise, you are going to dive deeper into Employee data at the film studio. Think about the different clauses you want to apply for each task.

1. Find the number of Artists in the studio (without a **HAVING** clause)
	1. SELECT COUNT(*) FROM employees WHERE Role = 'Artist';
2. Find the number of Employees of each role in the studio
	1. SELECT Role, Count(*) FROM employees GROUP BY Role;
3. Find the total number of years employed by all Engineers
	1. SELECT Sum(Years_employed) FROM employees WHERE Role = 'Engineer';

Exercise 11 — Tasks

1. Find the number of Artists in the studio (without a **HAVING** clause) ✓
2. Find the number of Employees of each role in the studio ✓
3. Find the total number of years employed by all Engineers ✓

This webpage is a lesson from SQLBolt covering the use of aggregate queries in SQL, specifically focusing on the HAVING clause.

The objective is to help users understand when and how to use the HAVING clause for more powerful SQL analytics.[1]

1


Here are some alternative ways to write the query that counts the number of employees whose role is 'Artist':

All of these queries will give you the count of employees with the role 'Artist', although the last one returns the role along with the count.

1


Here are different ways to write the query that counts employees for each role:

All of these variations provide a grouped count of employees by role, and you can tailor them depending on your requirements.

1


Here are different ways to write the query that gets the total years employed for all Engineers:

Each of these will give you the total years employed for all employees in the 'Engineer' role, using different approaches and features of SQL.

1