GK SOLUTIONS
AI • IoT • Arduino • Projects & Tutorials
DEFEAT THE FEAR
← Back to All Lessons

📈 Lesson 6: SQL Aggregation (Summarizing Data)

⏱️ Estimated time: 25 minutes | Difficulty: Intermediate

Power of Summary

Aggregate functions perform a calculation on a set of values and return a single value. These are essential for reports and data analysis.

Aggregate Functions

SELECT COUNT(*) FROM users;          -- Total rows
SELECT COUNT(email) FROM users;      -- Non-null emails
SELECT SUM(amount) FROM orders;      -- Total of all amounts
SELECT AVG(age) FROM users;          -- Average age
SELECT MAX(amount) FROM orders;      -- Highest amount
SELECT MIN(amount) FROM orders;      -- Lowest amount

GROUP BY

-- Count users per city
SELECT city, COUNT(*) AS user_count
FROM users
GROUP BY city;

-- Total sales per product
SELECT product, SUM(amount) AS total_sales
FROM orders
GROUP BY product
ORDER BY total_sales DESC;

HAVING (Filter Groups)

WHERE filters rows, HAVING filters groups after GROUP BY.

-- Cities with more than 5 users
SELECT city, COUNT(*) AS user_count
FROM users
GROUP BY city
HAVING COUNT(*) > 5;

-- Products with total sales over $1000
SELECT product, SUM(amount) AS total
FROM orders
GROUP BY product
HAVING SUM(amount) > 1000;

✅ Quick Quiz

❓ What's the difference between WHERE and HAVING?

❓ What does COUNT(*) return?

❓ What does GROUP BY do?

← Previous Next: INSERT, UPDATE, DELETE →