0
0
SQLquery~5 mins

Why aggregation is needed in SQL

Choose your learning style9 modes available
Introduction

Aggregation helps us summarize many rows of data into useful information like totals or averages.

When you want to find the total sales made in a month.
When you need to count how many customers bought a product.
When you want to calculate the average score of students in a class.
When you want to find the highest or lowest value in a list of numbers.
When you want to group data by categories and get summary numbers for each.
Syntax
SQL
SELECT AGGREGATE_FUNCTION(column_name) FROM table_name;

AGGREGATE_FUNCTION can be SUM, COUNT, AVG, MAX, MIN.

You can add GROUP BY to get summaries per group.

Examples
Counts the total number of rows in the orders table.
SQL
SELECT COUNT(*) FROM orders;
Adds up all the prices in the sales table.
SQL
SELECT SUM(price) FROM sales;
Finds the average score from the tests table.
SQL
SELECT AVG(score) FROM tests;
Finds the highest salary in each department.
SQL
SELECT department, MAX(salary) FROM employees GROUP BY department;
Sample Program

This creates a sales table, adds some rows, then sums the amount sold per product.

SQL
CREATE TABLE sales (id INT, product VARCHAR(20), amount INT);
INSERT INTO sales VALUES (1, 'apple', 10), (2, 'banana', 5), (3, 'apple', 15);
SELECT product, SUM(amount) FROM sales GROUP BY product;
OutputSuccess
Important Notes

Aggregation reduces many rows into fewer summary rows.

Without aggregation, you see raw data; with it, you see meaningful summaries.

Summary

Aggregation helps summarize data with functions like SUM, COUNT, AVG.

It is useful to get totals, averages, counts, and extremes.

GROUP BY lets you summarize data per category.