Group-By-Queries

With the GROUP BY clause you can sort information into groups according to one or more of its columns. It enables the use of some aggregate functions such as COUNT(), SUM(), AVG(), MAX(), and MIN() on rows of each group instead of the whole result set.

*Basic Group By

SELECT department, COUNT(*) AS total_employees
FROM employees
GROUP BY department;

*Group By With SUM()

    SELECT customer_id, SUM(amount) AS total_spent
    FROM orders
    GROUP BY customer_id;

*Group By Multiple Columns

SELECT department, job_title, COUNT(*) AS total
FROM employees
GROUP BY department, job_title;

*Group By With Having

SELECT department, COUNT(*) AS total
FROM employees
GROUP BY department
HAVING COUNT(*) > 5;

Why Use HAVING with GROUP BY in SQL?

  • The GROUP BY clause groups rows based on one or more columns.

  • The HAVING clause filters groups after aggregation (like WHERE but for groups instead of individual rows).