SQL Aggregate Functions

What are Aggregate Functions?

Aggregate functions perform calculations on multiple rows and return a single value.

COUNT()

SELECT COUNT(*) FROM employees;

SUM()

SELECT SUM(salary) FROM employees;

AVG()

SELECT AVG(salary) FROM employees;

MIN() and MAX()

SELECT MIN(salary), MAX(salary) FROM employees;

Using with WHERE

SELECT COUNT(*)
FROM employees
WHERE department = 'Sales';

Using with GROUP BY

SELECT department, AVG(salary)
FROM employees
GROUP BY department;

Multiple Aggregates

SELECT department,
       COUNT(*) AS total,
       AVG(salary) AS avg_salary
FROM employees
GROUP BY department;

Full Example

SELECT department,
       COUNT(*) AS total_employees,
       SUM(salary) AS total_salary,
       AVG(salary) AS avg_salary
FROM employees
GROUP BY department;

Why Aggregate Functions are Important

  • Summarize data
  • Perform analysis
  • Create reports
  • Generate insights

Common Mistakes

  • Missing GROUP BY when required
  • Mixing aggregated and non-aggregated columns
  • Forgetting WHERE before aggregation

Practice

Calculate total, average, and count for a table using aggregate functions.

SELECT 
-- add COUNT, SUM, AVG
FROM employees;

Need Help?

Ask the AI if you need help understanding or want to dive deeper in any topic