products
table and explore this step by step.
Recap of the Products Table
product_id | product_name | category | price | stock |
---|---|---|---|---|
1 | Wireless Mouse | Electronics | 1200 | 25 |
2 | Yoga Mat | Fitness | 800 | 50 |
3 | Bluetooth Speaker | Electronics | 2500 | 15 |
4 | Water Bottle | Fitness | 300 | 100 |
5 | Smartwatch | Electronics | 5000 | 10 |
What Are Aggregate Functions?
Aggregate functions perform calculations on a group of rows and return a single result. Common aggregate functions include:- COUNT(): Counts rows.
- SUM(): Adds values.
- AVG(): Calculates the average.
- MAX(): Finds the largest value.
- MIN(): Finds the smallest value.
COUNT: How Many Rows?
Say you want to know how many products are listed in your table.total_products |
---|
5 |
SUM: Total Stock
What’s the total stock across all products? Use the SUM function.total_stock |
---|
200 |
AVG: Average Price
What’s the average price of your products?average_price |
---|
1960 |
MAX and MIN: Highest and Lowest Prices
Want to find the most and least expensive products? Use MAX and MIN.highest_price | lowest_price |
---|---|
5000 | 300 |
GROUP BY: Aggregations by Category
What if you want to summarize your data by category? For example, how many products are there in each category? Enter the GROUP BY clause.category | total_products |
---|---|
Electronics | 3 |
Fitness | 2 |
category
and then counts the number of products in each group.
Combining GROUP BY with Other Functions
Let’s say you want to know the total stock in each category.category | total_stock |
---|---|
Electronics | 50 |
Fitness | 150 |
stock
column for each category.
Filtering Groups with HAVING
The HAVING clause is used to filter groups after they’ve been aggregated. For example, what if you want to see only the categories with more than 1 product?category | total_products |
---|---|
Electronics | 3 |
Fitness | 2 |
A Complex Query: Putting It All Together
Let’s find the total stock, average price, and count of products in each category, but only for categories with more than 1 product.category | total_stock | average_price | total_products |
---|---|---|---|
Electronics | 50 | 2900 | 3 |
Fitness | 150 | 550 | 2 |
Summary
Aggregations are the backbone of data analysis in SQL. By learning functions like COUNT, SUM, AVG, MAX, and MIN, and combining them with GROUP BY and HAVING, you can summarize and filter your data effectively. Practice these on your own data or stick with theproducts
table for now. Next, we’ll dive into joins, where we connect multiple tables to unlock even richer insights. Keep experimenting, and SQL will become second nature!