🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

GROUP BY Clause

SQL AggregationGroupingđŸŸĸ Free Lesson
SQL Aggregation

GROUP BY Clause

Collapse thousands of rows into meaningful summaries with grouping and aggregation.

  • Grouping — bucket rows by one or more columns
  • Aggregation — compute COUNT, SUM, AVG, MIN, MAX per group
  • Filtering Groups — use HAVING to filter after aggregation Turn detail into insight.

What Is GROUP BY?

GROUP BY PipelineRaw DataEng | AliceSales | BobEng | CarolSales | DanEng | EveGROUP BY deptEngEngEngSalesSalesAggregateCOUNT(*):3, 2SUM(salary):210k,120kAVG(salary):70k, 60kResultEng | 3 | 210kSales | 2 | 120k
SELECT department, COUNT(*) AS employee_count
FROM employees
GROUP BY department;

Syntax

SELECT
    column1,
    aggregate_function(column2)
FROM table_name
GROUP BY column1;
ElementPurpose
GROUP BYDefines the grouping column(s)
SELECTColumns to display — must be aggregated or in GROUP BY
Aggregate functionCOUNT, SUM, AVG, MIN, MAX, etc.

Basic Example

-- Count employees and average salary per department
SELECT
    department,
    COUNT(*) AS employee_count,
    ROUND(AVG(salary), 2) AS avg_salary
FROM employees
GROUP BY department
ORDER BY avg_salary DESC;

Single Column Grouping

-- Total salary expenditure per department
SELECT
    department,
    COUNT(*) AS headcount,
    SUM(salary) AS total_salary,
    MIN(salary) AS min_salary,
    MAX(salary) AS max_salary
FROM employees
GROUP BY department;
DepartmentHeadcountTotal SalaryMinMax
Engineering4560,000$150,000
Marketing2045,000$110,000
Sales3540,000$120,000

Multiple Column Grouping

-- Breakdown by department and job title
SELECT
    department,
    job_title,
    COUNT(*) AS employee_count,
    AVG(salary) AS avg_salary
FROM employees
GROUP BY department, job_title
ORDER BY department, avg_salary DESC;

-- Monthly revenue by product
SELECT
    YEAR(order_date) AS order_year,
    MONTH(order_date) AS order_month,
    product_id,
    COUNT(*) AS order_count,
    SUM(total_amount) AS total_revenue
FROM orders
GROUP BY YEAR(order_date), MONTH(order_date), product_id
ORDER BY order_year, order_month, total_revenue DESC;

WHERE vs HAVING

ClauseFiltersTimingCan Use Aggregates
WHEREIndividual rowsBefore GROUP BYNo
HAVINGGroupsAfter GROUP BYYes

Query Execution Order

-- WHERE filters rows first, then GROUP BY groups, then HAVING filters groups
SELECT
    department,
    COUNT(*) AS emp_count,
    AVG(salary) AS avg_salary
FROM employees
WHERE status = 'Active'            -- Step 1: filter rows
GROUP BY department                 -- Step 2: group remaining rows
HAVING AVG(salary) > 75000         -- Step 3: filter groups
ORDER BY avg_salary DESC;          -- Step 4: sort

Examples

-- WHERE: filter before grouping (only active employees)
SELECT department, COUNT(*) AS emp_count
FROM employees
WHERE status = 'Active'
GROUP BY department;

-- HAVING: filter after grouping (departments with more than 5 people)
SELECT department, COUNT(*) AS emp_count
FROM employees
GROUP BY department
HAVING COUNT(*) > 5;

-- Combined: active employees, grouped, then filter high-paying departments
SELECT
    department,
    COUNT(*) AS emp_count,
    AVG(salary) AS avg_salary
FROM employees
WHERE status = 'Active'
GROUP BY department
HAVING AVG(salary) > 75000
ORDER BY avg_salary DESC;

GROUP BY with NULLs

NULL values form their own group in GROUP BY.

-- NULLs are grouped together
SELECT
    department_id,
    COUNT(*) AS employee_count
FROM employees
GROUP BY department_id
ORDER BY department_id;

-- Replace NULLs with a default value for cleaner output
SELECT
    COALESCE(department_id, 0) AS department_id,
    COUNT(*) AS employee_count
FROM employees
GROUP BY COALESCE(department_id, 0);

GROUP BY with ROLLUP and CUBE

-- ROLLUP: adds subtotals and a grand total
SELECT
    department,
    job_title,
    COUNT(*) AS employee_count
FROM employees
GROUP BY ROLLUP (department, job_title);

-- CUBE: all possible subtotals (not supported in MySQL)
SELECT
    department,
    job_title,
    COUNT(*) AS employee_count
FROM employees
GROUP BY CUBE (department, job_title);
ExtensionSubtotals Generated
GROUP BYIndividual groups only
ROLLUPHierarchical subtotals + grand total
CUBEAll possible subtotal combinations + grand total

GROUP BY with JOINs

-- Aggregate order data joined with customer info
SELECT
    c.first_name,
    c.last_name,
    COUNT(o.order_id) AS order_count,
    SUM(o.total_amount) AS total_spent
FROM customers c
INNER JOIN orders o ON c.customer_id = o.customer_id
GROUP BY c.customer_id, c.first_name, c.last_name
HAVING COUNT(o.order_id) > 5
ORDER BY total_spent DESC;

Performance Considerations

FactorRecommendation
IndexesCreate indexes on GROUP BY columns
SortingGROUP BY may require implicit sorting
MemoryLarge groups can exceed memory limits
StatisticsKeep table statistics current
Execution planUse EXPLAIN to verify index usage
-- Index recommendations for common GROUP BY patterns
CREATE INDEX idx_employees_department ON employees(department);
CREATE INDEX idx_employees_dept_job ON employees(department, job_title);
CREATE INDEX idx_orders_date ON orders(order_date);
CREATE INDEX idx_orders_product_date ON orders(product_id, order_date);

Practice Exercises

Exercise 1: Count the number of employees in each department.

-- Solution
SELECT department, COUNT(*) AS employee_count
FROM employees
GROUP BY department
ORDER BY employee_count DESC;

Exercise 2: Find the average salary per department for departments with more than 10 employees.

-- Solution
SELECT
    department,
    COUNT(*) AS employee_count,
    ROUND(AVG(salary), 2) AS avg_salary
FROM employees
GROUP BY department
HAVING COUNT(*) > 10
ORDER BY avg_salary DESC;

Exercise 3: Generate a monthly sales report for 2024 with order count, total revenue, and average order value.

-- Solution
SELECT
    MONTH(order_date) AS month_number,
    MONTHNAME(order_date) AS month_name,
    COUNT(*) AS order_count,
    SUM(total_amount) AS total_revenue,
    ROUND(AVG(total_amount), 2) AS avg_order_value
FROM orders
WHERE YEAR(order_date) = 2024
GROUP BY MONTH(order_date), MONTHNAME(order_date)
ORDER BY month_number;

See Also


Extended Learning: Beyond the Basics

Key Concepts Summary

This lesson covers fundamental concepts that serve as building blocks for more advanced topics. Master these basics before moving to intermediate and advanced material.

Prerequisite Knowledge

Before studying this topic in depth, ensure you understand:

  • Basic definitions and terminology
  • Core formulas and their derivations
  • Common applications in real-world scenarios
  • Typical pitfalls and misconceptions

Step-by-Step Walkthrough

Let us work through a complete example to solidify understanding:

Step 1: Identify the problem type. Determine which category this problem falls into and which approach is most appropriate.

Step 2: Apply the relevant formula. Substitute known values into the appropriate equation, paying attention to units and constraints.

Step 3: Simplify and solve. Work through the algebra step by step, checking each intermediate result.

Step 4: Verify the answer. Check that the solution satisfies the original conditions and makes logical sense.

Common Mistakes to Avoid

  1. Misidentifying the problem type — Always start by categorizing the problem
  2. Incorrect formula application — Verify the formula applies to your specific case
  3. Unit errors — Always check units are consistent throughout
  4. Sign errors — Pay careful attention to positive and negative values
  5. Rounding too early — Keep full precision until the final answer
  6. Forgetting constraints — Check that solutions satisfy all given conditions

Real-World Applications

Understanding this concept is essential for:

  • Advanced problem solving in examinations
  • Building intuition for more complex topics
  • Developing analytical thinking skills
  • Applying mathematical reasoning to practical situations

Practice Exercises

  1. Basic: Solve 5 problems of increasing difficulty using the core concept.
  2. Intermediate: Apply the concept to word problems with multiple steps.
  3. Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
  4. Challenge: Create your own problem that requires this concept plus additional knowledge.

Interview and Exam Tips

  • Common question patterns: Identify which exam or interview formats test this topic
  • Time management: Practice completing problems within time constraints
  • Common traps: Know the typical mistakes examiners set as distractors
  • Verification strategy: Develop a quick method to check your answer

Related Topics

Quick Reference Card

ConceptFormula/RuleKey InsightCommon Use
Core DefinitionSee main textUnderstand the intuitionFoundation for all applications
Key FormulaSee main textMemorize the derivationDirect problem solving
Special CaseSee main textRecognize when it appliesSimplifies complex problems
Edge CaseSee main textKnow the limitationsAvoids errors

Further Reading

For students who want to go deeper:

  • Standard textbooks on the subject
  • Research papers applying this concept
  • Online courses with video explanations
  • Practice problem collections with detailed solutions
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-11-14

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert SQL Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement