πŸ” HAVING – Filtering Groups After GROUP BY

(because sometimes you need to filter the results after SQL has already grouped the data)

πŸ”§ Quick Syntax

SELECT column, aggregate_function(column)
FROM table
GROUP BY column
HAVING condition;

This tells SQL:
“Group the data by a column, apply aggregate functions, and then filter the groups based on a condition.”

πŸ‘€ Imagine You Have This sales Table Again:

sale_idproductquantitysale_date
1Laptop32024-01-01
2Phone52024-01-01
3Laptop22024-01-02
4Phone32024-01-02
5Laptop42024-01-03
6Phone72024-01-03

Scenario: You want to find products where the total quantity sold is greater than 6.

πŸ”§ Using HAVING to Filter Grouped Data

Here’s how to group by product and then use HAVING to filter groups based on the total quantity sold:

SELECT product, SUM(quantity) AS total_quantity
FROM sales
GROUP BY product
HAVING SUM(quantity) > 6;

βœ… Result:

producttotal_quantity
Phone15

πŸ” HAVING vs WHERE

ClauseWhen It’s Used
WHEREFilters rows before grouping
HAVINGFilters groups after the data is grouped

Where to use:
– Use WHERE for filtering individual rows.
– Use HAVING for filtering after the data is grouped.

πŸ§ƒ Recap

  • HAVING is used to filter groups after data has been grouped with GROUP BY.
  • It is especially useful with aggregate functions (like SUM, AVG, COUNT) to filter the results based on aggregated values.
  • WHERE filters data before grouping, while HAVING filters after grouping.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top