TGViewer
SQL Programming Resources SQL Programming Resources @sqlanalyst ยท 76.7K subscribers
Post #2225 4.17K
โœ… SQL GROUP BY HAVING ๐Ÿ“Š

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
  • โค 8
More from @sqlanalyst
  1. Oct 13, 2026SQL Interview Series โ€” Part 8 ๐Ÿ“Œ Question 8: Find Customers Who Have Never Placed an Orderโ€ฆ
  2. Oct 13, 2026๐—ง๐—ข๐—ฃ ๐—™๐—ฅ๐—˜๐—˜ ๐—–๐—ข๐—จ๐—ฅ๐—ฆ๐—˜๐—ฆ ๐—ง๐—ข ๐—•๐—ข๐—ข๐—ฆ๐—ง ๐—ฌ๐—ข๐—จ๐—ฅ ๐—ฆ๐—ž๐—œ๐—Ÿ๐—Ÿ๐—ฆ ๐—œ๐—ก ๐Ÿฎ๐Ÿฌ๐Ÿฎ๐Ÿฒ! Explorโ€ฆ
  3. Oct 12, 2026SQL Interview Series โ€” Part 6 ๐Ÿ“Œ Question 6: Find the Top 2 Highest-Paid Employees in Eachโ€ฆ
  4. Oct 12, 2026๐Ÿš€ ๐—ช๐—ต๐—ถ๐—ฐ๐—ต ๐—ง๐—ฒ๐—ฐ๐—ต ๐—ฆ๐—ธ๐—ถ๐—น๐—น ๐—ช๐—ถ๐—น๐—น ๐—ฌ๐—ผ๐˜‚ ๐— ๐—ฎ๐˜€๐˜๐—ฒ๐—ฟ ๐—ถ๐—ป ๐Ÿฎ๐Ÿฌ๐Ÿฎ๐Ÿฒ? Want to builโ€ฆ
  5. Oct 9, 2026SQL Interview Series โ€” Part 5 ๐Ÿ“Œ Question 5: Find Employees Who Earn More Than Their Managโ€ฆ
  6. Oct 9, 2026๐Ÿ‡ฎ๐Ÿ‡ณ ๐—š๐—ข๐—ฉ๐—˜๐—ฅ๐—ก๐— ๐—˜๐—ก๐—ง ๐—ข๐—™ ๐—œ๐—ก๐——๐—œ๐—” โ€” ๐—”๐—œ๐—–๐—ง๐—˜ ๐—œ๐—ก๐—ง๐—˜๐—ฅ๐—ก๐—ฆ๐—›๐—œ๐—ฃ๐—ฆ ๐Ÿฎ๐Ÿฌ๐Ÿฎ๐Ÿฒ ๐Ÿš€โ€ฆ
Threads Profile ViewerView any public Threads profile without an account.Open ThreadLook โ†’Writing with AI? Make it sound human.Metric37 rewrites AI drafts so they read naturally. Free AI detector, 1,500 words free.Try Metric37 โ†’