Introduction
Aggregation helps us quickly find summary information from many rows of data. It turns lots of details into simple answers.
Aggregation helps us quickly find summary information from many rows of data. It turns lots of details into simple answers.
SELECT AGGREGATE_FUNCTION(column_name) FROM table_name;
AGGREGATE_FUNCTION can be SUM, COUNT, AVG, MAX, MIN, etc.
You can add GROUP BY to get summaries per group.
SELECT COUNT(*) FROM orders;
SELECT AVG(price) FROM products;
SELECT category, SUM(quantity) FROM sales GROUP BY category;
This example creates a sales table, adds some data, and then sums the quantity sold per category.
CREATE TABLE sales ( id SERIAL PRIMARY KEY, category TEXT, quantity INT ); INSERT INTO sales (category, quantity) VALUES ('Books', 10), ('Books', 5), ('Toys', 7), ('Toys', 3), ('Clothes', 8); SELECT category, SUM(quantity) AS total_quantity FROM sales GROUP BY category ORDER BY category;
Aggregation functions ignore NULL values by default.
Use GROUP BY to get summaries for each group instead of the whole table.
Aggregation turns many rows into simple summary numbers.
Common functions include COUNT, SUM, AVG, MAX, and MIN.
GROUP BY helps get summaries for each category or group.
COUNT or SUM in SQL?sales?SELECT COUNT(*) FROM table_name;.orders with columns customer_id and amount, what does this query return?SELECT customer_id, SUM(amount) FROM orders GROUP BY customer_id;
SELECT customer_id, COUNT(*) FROM orders;
Pass the test and this pattern moves unknown