Introduction
GROUP BY helps you organize data into groups so you can calculate totals or averages for each group.
Jump into concepts and practice - no test required
GROUP BY helps you organize data into groups so you can calculate totals or averages for each group.
SELECT column1, AGGREGATE_FUNCTION(column2) FROM table_name GROUP BY column1;
The column in GROUP BY is the one you want to group your data by.
AGGREGATE_FUNCTION can be COUNT, SUM, AVG, MAX, or MIN.
SELECT department, COUNT(*) FROM employees GROUP BY department;
SELECT product, SUM(quantity) FROM sales GROUP BY product;
SELECT class, AVG(score) FROM tests GROUP BY class;
This example creates a sales table, adds some sales data, and then shows the total quantity sold for each product.
CREATE TABLE sales ( product VARCHAR(20), quantity INT ); INSERT INTO sales VALUES ('Apple', 10), ('Banana', 5), ('Apple', 15), ('Banana', 7), ('Orange', 8); SELECT product, SUM(quantity) AS total_quantity FROM sales GROUP BY product;
Every column in SELECT that is not inside an aggregate function must be in the GROUP BY clause.
GROUP BY helps summarize data by categories.
GROUP BY groups rows that have the same values in specified columns.
Aggregate functions calculate values like sum, count, or average for each group.
Use GROUP BY when you want to see summary information for categories.
GROUP BY clause do in an SQL query?GROUP BY to count employees per department?SELECT department, COUNT(*) FROM employees GROUP BY department; correctly groups by department and counts employees. The other options have syntax errors: missing column after GROUP BY, no GROUP BY clause, or invalid WHERE syntax.sales with columns region and amount, what is the result of this query?SELECT region, SUM(amount) FROM sales GROUP BY region;
SELECT department, AVG(salary) FROM employees WHERE department GROUP BY department;
products table with columns category, price, and stock. Which query shows the average price and total stock for each category, but only for categories with more than 10 products?SELECT category, AVG(price), SUM(stock) FROM products GROUP BY category HAVING COUNT(*) > 10; correctly uses GROUP BY then HAVING. Using WHERE with COUNT(*) is invalid (WHERE processes rows before grouping), and placing HAVING before GROUP BY or incorrect clause ordering is invalid syntax.