The SQL Server SELECT statement in 60 seconds - the HAVING Clause #shorts

preview_player
Показать описание
In 60 seconds we'll explore the HAVING clause in SQL.
My SQL Server Udemy courses are:
----
In this short video, I'm going to show you how to use the SQL HAVING clause. I'll explain what it is and how to use it, in just 60 seconds!

If you're new to SQL, then this video is for you! I'll show you how to use the SQL HAVING clause, which is a very important part of the SQL language. By the end of this video, you'll be able to use the HAVING clause to filter your data in a smart way!

The HAVING clause is the fifth clause in the SELECT statement in SQL, after the SELECT, FROM, WHERE, and GROUP BY.

The optional WHERE clause looks at individual rows retrieved in the FROM clause, and creates a reduced dataset. You should use it when looking at individual rows.

SELECT schema_id, type, COUNT(*) AS NumberOfObjects
WHERE type like '%P%' -- this works, as it looks at individual rows
GROUP BY schema_id, type

It does not work when using aggregations.

SELECT schema_id, type, COUNT(*) AS NumberOfObjects
WHERE COUNT(*)=10 -- does not work, as it uses an aggregation
GROUP BY schema_id, type

The HAVING clause looks at the response after the GROUP BY clause. You should use it based on aggregations, such as SUM, COUNT, AVG, MIN and MAX, such as those shown in the SELECT clause.

SELECT schema_id, type, COUNT(*) AS NumberOfObjects
GROUP BY schema_id, type
HAVING COUNT(*)=10 -- this works, using an aggregation

However, you may be able to use other aggregations as well.

SELECT schema_id, type, COUNT(*) AS NumberOfObjects
GROUP BY schema_id, type
HAVING SUM(schema_id)=10

The HAVING clause is the least used clause in the SELECT statement – use it to focus based on the results after the GROUP BY clause.

----
Links to my website are:
Рекомендации по теме