Grouping in SQL is used to arrange identical data into groups. It is typically used with aggregate functions like COUNT()
, SUM()
, AVG()
, MAX()
, and MIN()
to perform operations on each group of data.
🔍 Pro Tip: Grouping makes analyzing data more organized by summarizing results into categories.
Grouping allows you to break down your dataset into meaningful categories. It's especially useful in data analysis where you need to summarize or aggregate data based on certain criteria.
WHERE
, but for groups)SELECT column_name, AGGREGATE_FUNCTION(column_name) FROM table_name WHERE condition GROUP BY column_name ORDER BY column_name;
Example 1: Count the number of employees in each department:
SELECT department, COUNT(*) FROM employees GROUP BY department;
Example 2: Get the average salary of employees in each department:
SELECT department, AVG(salary) FROM employees GROUP BY department;
The HAVING
clause is used to filter groups after the GROUP BY
operation. It's often used in conjunction with aggregate functions to filter aggregated results.
Example 3: Get departments with an average salary greater than $50,000:
SELECT department, AVG(salary) FROM employees GROUP BY department HAVING AVG(salary) > 50000;
The ORDER BY
clause can be used to sort the grouped data. It's often useful when you want to see the results in ascending or descending order of aggregate values.
Example 4: Sort departments by average salary in descending order:
SELECT department, AVG(salary) FROM employees GROUP BY department ORDER BY AVG(salary) DESC;
SELECT *
when using GROUP BY. Specify only the necessary columns.
✅ Next Step: Experiment with GROUP BY
and HAVING
in your own SQL queries!
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!