πŸ”Ή GROUP BY Command

Definition: The GROUP BY statement groups rows that have the same values in specified columns into summary rows, often used with aggregate functions like COUNT(), SUM(), AVG(), etc.
Syntax:
SELECT column_name, AGGREGATE_FUNCTION(column_name)
FROM table_name
GROUP BY column_name;
Example:
Show the total salary department-wise.
SELECT department, SUM(salary) AS total_salary
FROM employees
GROUP BY department;
Sample employees table:
namedepartmentsalary
AliceIT60000
BobHR50000
CharlieIT70000
DaisyHR55000
EveFinance80000
🟒 Result:
departmenttotal_salary
IT130000
HR105000
Finance80000
πŸ” How the Output Was Calculated:
  • All rows were grouped based on the department column.
  • Then, SUM(salary) was applied within each group.
  • IT group had 2 salaries: 60000 and 70000 β†’ Total = 130000.
  • HR group had 2 salaries: 50000 and 55000 β†’ Total = 105000.
  • Finance group had 1 salary: 80000 β†’ Total = 80000.
That’s how you got one result per department, each with a total salary.
When to Use: Use GROUP BY when you want to calculate totals, averages, counts, or other statistics for each group of data based on a column.
Common Mistake:
❌ Selecting columns that are not part of the GROUP BY clause or an aggregate function.
SELECT department, name FROM employees GROUP BY department;
πŸ”΄ This will give an error unless your SQL dialect supports it.
πŸ”Ž Tip: Always pair GROUP BY with aggregate functions unless all selected columns are grouped.
Real-world Use Case:
Find how many employees are there in each department:
SELECT department, COUNT(*) AS emp_count
FROM employees
GROUP BY department;
πŸ‘‰ Next Topic: HAVING Clause