What is GROUP BY?
GROUP BY is used to group rows that have the same values in one or more columns. Itโs mostly used with aggregate functions like SUM(), COUNT(), AVG() to get summarized results.
What is HAVING?
HAVING is like WHERE, but it works after grouping. It filters the grouped results. You canโt use aggregate functions in WHERE, so we use HAVING instead.
๐ Problem 1:
You want to find total sales made in each city.
SELECT city, SUM(sales) AS total_sales
FROM customers
GROUP BY city;
โ This groups the sales by city and shows total per group.
๐ Problem 2:
Now, show only those cities where total sales are above โน50,000.
SELECT city, SUM(sales) AS total_sales
FROM customers
GROUP BY city
HAVING total_sales > 50000;
โ `HAVING filters the result after grouping.
๐ Problem 3:
Find departments with more than 10 active employees.
SELECT department, COUNT(*) AS emp_count
FROM employees
WHERE active = 1
GROUP BY department
HAVING emp_count > 10;
โ First, we filter rows using
WHERE. Then group, then filter groups with HAVING.๐ก Use
GROUP BY to summarize, HAVING to filter those summaries.Double Tap โฅ๏ธ For More