0
0
SQLquery~5 mins

Combining multiple aggregates in SQL

Choose your learning style9 modes available
Introduction
We use multiple aggregates to get different summary numbers from data in one query. This helps us understand data better in one go.
When you want to find the total and average sales in one report.
When you need to count how many items and find the maximum price at the same time.
When you want to see the smallest and largest values in a column together.
When you want to get multiple summary statistics like sum, count, and average for a group of data.
Syntax
SQL
SELECT AGGREGATE_FUNCTION1(column), AGGREGATE_FUNCTION2(column), ... FROM table_name;
AGGREGATE_FUNCTION can be SUM, COUNT, AVG, MIN, MAX, etc.
You can combine many aggregates separated by commas in the SELECT clause.
Examples
Counts all rows and sums the price column in the sales table.
SQL
SELECT COUNT(*), SUM(price) FROM sales;
Finds average, maximum, and minimum age from the users table.
SQL
SELECT AVG(age), MAX(age), MIN(age) FROM users;
Counts unique categories and sums quantity in products.
SQL
SELECT COUNT(DISTINCT category), SUM(quantity) FROM products;
Sample Program
This creates a table orders, adds three rows, then shows total orders, total amount, and average amount in one query.
SQL
CREATE TABLE orders (id INT, amount DECIMAL);
INSERT INTO orders VALUES (1, 100.50), (2, 200.00), (3, 50.25);
SELECT COUNT(id) AS total_orders, SUM(amount) AS total_amount, AVG(amount) AS average_amount FROM orders;
OutputSuccess
Important Notes
Make sure to use aliases (AS) to name your result columns for clarity.
Aggregates ignore NULL values except COUNT(*), which counts all rows.
You can combine aggregates with GROUP BY to get summaries per group.
Summary
Multiple aggregates let you get many summary numbers in one query.
Use commas to separate aggregate functions in the SELECT clause.
Always check your results with aliases to understand the output.