SQL AVG() Function
The AVG()
function in SQL is used to calculate the average value of a numeric column in a table. Here's a detailed explanation with examples:
Syntax
SELECT AVG(column_name) FROM table_name;
Example 1: Basic Usage
Consider a table employees
with the following data:
id |
name |
salary |
1 |
Alice |
50000 |
2 |
Bob |
60000 |
3 |
Charlie |
55000 |
4 |
Diana |
70000 |
5 |
Edward |
45000 |
To find the average salary of all employees:
SELECT AVG(salary) AS average_salary FROM employees;
Output:
Example 2: Using AVG() with a WHERE Clause
To find the average salary of employees with a salary greater than 50000:
SELECT AVG(salary) AS average_salary FROM employees WHERE salary > 50000;
Output:
Example 3: Grouping Results with AVG()
Consider another table sales
with the following data:
id |
salesperson |
region |
sales_amount |
1 |
Alice |
North |
1000 |
2 |
Bob |
South |
1500 |
3 |
Charlie |
North |
2000 |
4 |
Diana |
East |
3000 |
5 |
Edward |
West |
2500 |
To find the average sales amount by region:
SELECT region, AVG(sales_amount) AS average_sales FROM sales GROUP BY region;
Output:
region |
average_sales |
East |
3000.00 |
North |
1500.00 |
South |
1500.00 |
West |
2500.00 |
Example 4: Combining AVG() with Other Aggregate Functions
To find the total sales and the average sales amount by region:
SELECT region, SUM(sales_amount) AS total_sales, AVG(sales_amount) AS average_sales FROM sales GROUP BY region;
Output:
region |
total_sales |
average_sales |
East |
3000 |
3000.00 |
North |
3000 |
1500.00 |
South |
1500 |
1500.00 |
West |
2500 |
2500.00 |
These examples illustrate how the AVG()
function can be used in various scenarios to compute average values in SQL.