SQL GROUP BY Get Certified
Learn how to group rows that share the same values and calculate summaries with COUNT, SUM, AVG, MIN and MAX using the GROUP BY clause.
What is the GROUP BY Clause?
The GROUP BY clause gathers rows that have identical values in one or more columns into groups. Once the rows are grouped, aggregate functions can produce a single summary value for each group.
GROUP BY is one of the most important tools for turning raw transactional data into meaningful reports.
Basic GROUP BY Syntax
Place the column (or columns) you want to group by after the GROUP BY keyword. Any non-aggregated column that appears in the SELECT list must also appear in the GROUP BY list.
What this code does: Groups the sales rows by category and counts how many items belong to each category. Stationery has 3 items and Electronics has 2. The query returns 2 rows.
WITH sales(sale_id, product, category, amount) AS (
VALUES
(1, 'Notebook', 'Stationery', 500),
(2, 'Pen Set', 'Stationery', 300),
(3, 'Desk Lamp', 'Electronics', 1200),
(4, 'USB Cable', 'Electronics', 700),
(5, 'Marker Set', 'Stationery', 450)
)
SELECT
category,
COUNT(*) AS total_items
FROM sales
GROUP BY category
ORDER BY category;
GROUP BY with COUNT()
COUNT(*) is the most common aggregate used with GROUP BY. It tells you how many rows fall into each group.
What this code does: Counts the number of orders placed from each city. Delhi has 3 orders, Mumbai has 2 and Pune has 1. The result is sorted by the count in descending order.
WITH orders(order_id, customer, city) AS (
VALUES
(101, 'Aarav', 'Delhi'),
(102, 'Meera', 'Mumbai'),
(103, 'Kabir', 'Delhi'),
(104, 'Riya', 'Pune'),
(105, 'Tara', 'Mumbai'),
(106, 'Dev', 'Delhi')
)
SELECT
city,
COUNT(*) AS order_count
FROM orders
GROUP BY city
ORDER BY order_count DESC;
GROUP BY with SUM()
SUM() adds up the numeric values inside each group.
What this code does: Calculates the total amount paid by each payment method. UPI has the highest total (2400), followed by Card (2000) and Cash (1200).
WITH payments(payment_id, method, amount) AS (
VALUES
(1, 'Card', 1200),
(2, 'Cash', 500),
(3, 'Card', 800),
(4, 'UPI', 1500),
(5, 'Cash', 700),
(6, 'UPI', 900)
)
SELECT
method,
SUM(amount) AS total_amount
FROM payments
GROUP BY method
ORDER BY total_amount DESC;
GROUP BY with AVG()
AVG() returns the average of the values inside each group. The result is often rounded for readability.
What this code does: Computes the average marks for each subject. Science averages 85 and Math averages 81.33. The query returns 2 rows.
WITH exam_results(student_id, student_name, subject, marks) AS (
VALUES
(1, 'Anaya', 'Math', 82),
(2, 'Rohan', 'Math', 74),
(3, 'Ishita', 'Science', 91),
(4, 'Karan', 'Science', 79),
(5, 'Mira', 'Math', 88),
(6, 'Dev', 'Science', 85)
)
SELECT
subject,
ROUND(AVG(marks), 2) AS average_marks
FROM exam_results
GROUP BY subject
ORDER BY subject;
GROUP BY with MIN() and MAX()
MIN() and MAX() find the smallest and largest values inside each group.
What this code does: For every city it returns the lowest and highest recorded temperatures. Delhi ranges from 31 to 38, Pune from 27 to 33, and Jaipur from 36 to 40.
WITH temperatures(reading_id, city, temperature) AS (
VALUES
(1, 'Delhi', 34),
(2, 'Delhi', 38),
(3, 'Delhi', 31),
(4, 'Pune', 29),
(5, 'Pune', 33),
(6, 'Pune', 27),
(7, 'Jaipur', 36),
(8, 'Jaipur', 40)
)
SELECT
city,
MIN(temperature) AS lowest_temperature,
MAX(temperature) AS highest_temperature
FROM temperatures
GROUP BY city
ORDER BY city;
GROUP BY Multiple Columns
You can list several columns after GROUP BY. SQL then creates a separate group for every unique combination of those columns.
What this code does: Groups sales by both store and category, then sums the amount for each combination. Central-Books totals 1200, Central-Games 1200, West-Books 1000 and West-Games 900.
WITH store_sales(sale_id, store, category, amount) AS (
VALUES
(1, 'Central', 'Books', 500),
(2, 'Central', 'Books', 700),
(3, 'Central', 'Games', 1200),
(4, 'West', 'Books', 400),
(5, 'West', 'Games', 900),
(6, 'West', 'Books', 600)
)
SELECT
store,
category,
SUM(amount) AS total_sales
FROM store_sales
GROUP BY store, category
ORDER BY store, category;
GROUP BY with WHERE
The WHERE clause is evaluated before the rows are grouped. Use it to discard individual rows that should never enter the groups.
What this code does: First keeps only transactions whose amount is at least 600, then groups the remaining rows by category and sums them. Books totals 900 and Games totals 3300.
WITH transactions(transaction_id, category, amount) AS (
VALUES
(1, 'Books', 450),
(2, 'Books', 900),
(3, 'Games', 1200),
(4, 'Games', 600),
(5, 'Books', 300),
(6, 'Games', 1500)
)
SELECT
category,
SUM(amount) AS total_amount
FROM transactions
WHERE amount >= 600
GROUP BY category
ORDER BY category;
GROUP BY with HAVING
The HAVING clause is evaluated after the groups have been formed. It is the place to filter on aggregate results.
What this code does: Calculates total sales per department and then keeps only those departments whose total exceeds 2000. Electronics (4300) and Books (2100) remain; Clothing is filtered out.
WITH department_sales(sale_id, department, amount) AS (
VALUES
(1, 'Books', 1200),
(2, 'Books', 900),
(3, 'Electronics', 2500),
(4, 'Electronics', 1800),
(5, 'Clothing', 700),
(6, 'Clothing', 600)
)
SELECT
department,
SUM(amount) AS total_sales
FROM department_sales
GROUP BY department
HAVING SUM(amount) > 2000
ORDER BY total_sales DESC;
HAVING with COUNT()
A very common pattern is to keep only groups that contain a minimum number of rows.
What this code does: Counts students per course and keeps only courses that have at least two registrations. SQL (3) and Python (2) remain; HTML is dropped.
WITH registrations(registration_id, course, student) AS (
VALUES
(1, 'SQL', 'Aarav'),
(2, 'SQL', 'Meera'),
(3, 'SQL', 'Kabir'),
(4, 'Python', 'Riya'),
(5, 'Python', 'Dev'),
(6, 'HTML', 'Tara')
)
SELECT
course,
COUNT(*) AS student_count
FROM registrations
GROUP BY course
HAVING COUNT(*) >= 2
ORDER BY student_count DESC;
GROUP BY with ORDER BY
After the groups are calculated you can sort them with a normal ORDER BY clause.
What this code does: Sums the sales for each month and sorts the months from highest total to lowest. March leads with 4000, followed by January (3700) and February (2700).
WITH monthly_sales(sale_id, month_name, amount) AS (
VALUES
(1, 'January', 1500),
(2, 'January', 2200),
(3, 'February', 1800),
(4, 'February', 900),
(5, 'March', 2700),
(6, 'March', 1300)
)
SELECT
month_name,
SUM(amount) AS total_sales
FROM monthly_sales
GROUP BY month_name
ORDER BY total_sales DESC;
Multiple Aggregate Functions in One Query
You can request several statistics for the same groups in a single SELECT list.
What this code does: For every department it returns the number of employees, the total salary bill, the average salary, and the lowest and highest individual salaries.
WITH employee_payments(payment_id, department, salary) AS (
VALUES
(1, 'Design', 42000),
(2, 'Design', 48000),
(3, 'Engineering', 65000),
(4, 'Engineering', 72000),
(5, 'Marketing', 45000),
(6, 'Marketing', 52000)
)
SELECT
department,
COUNT(*) AS employee_count,
SUM(salary) AS total_salary,
ROUND(AVG(salary), 2) AS average_salary,
MIN(salary) AS lowest_salary,
MAX(salary) AS highest_salary
FROM employee_payments
GROUP BY department
ORDER BY department;
WHERE vs HAVING
Common Aggregate Functions
Advantages of GROUP BY
- Turns detailed rows into clear, summarized groups.
- Works seamlessly with all major aggregate functions.
- Supports grouping by one or many columns.
- Combines cleanly with WHERE, HAVING and ORDER BY.
- Essential for almost every analytical or reporting query.
Best Practices
- Put every non-aggregated column that appears in SELECT into the GROUP BY list.
- Use WHERE to discard unwanted rows before they are grouped.
- Use HAVING when the filter must be based on an aggregate result.
- Give clear aliases to calculated columns (e.g. total_sales, average_marks).
- Sort the final result with ORDER BY so the report is easy to read.
- Prefer COUNT(*) when you simply want the number of rows in each group.
The GROUP BY clause is the foundation of SQL summarization. Combined with aggregate functions it lets you count, total, average and find extremes for every meaningful group of rows. Click Test My Code on any example to run it live, or Code Explanation to walk through the query block by block.
🧪 Test Your SQL Code
Edit the SQL code on the left and click “Run Code” to see the result on the right.
Click “Run Code” to see the result here.