Calculating Averages with SQL AVG

The AVG() function in SQL is used to calculate the average value of a numeric column. It is an aggregate function, meaning it computes a single result from a set of values. The AVG() function is useful for a variety of scenarios, such as finding the average salary of employees, calculating average order amounts, or determining average scores in a grading system. This chapter will explore the AVG() function in depth, from basic syntax to advanced use cases, including examples, code, and output explanations.

Basic Syntax of SQL AVG()

The basic syntax of the AVG() function is straightforward. It is used with the SELECT statement and takes a numeric column as an argument.

Syntax:

				
					SELECT AVG(column_name) 
FROM table_name
WHERE condition;

				
			
  • column_name: The column whose values you want to average.
  • table_name: The table containing the data.
  • condition: An optional condition to filter the rows.

Example 1: Basic AVG of Salaries

Consider a table employees with the following data:

idnamedepartmentsalary
1John DoeHR5000
2Jane SmithIT6000
3David GreenSales7000
4Sarah BrownIT8000
5James WhiteSales5500

To calculate the average salary of all employees:

Query:

				
					SELECT AVG(salary) AS AverageSalary
FROM employees;

				
			

Output:

AverageSalary
6300

The query calculates the average salary of all employees, which is 6,300.

Using AVG() with WHERE Clause

You can combine the AVG() function with the WHERE clause to filter the data and calculate the average for a specific subset of rows.

Example 2: Average Salary in the IT Department

To calculate the average salary of employees in the IT department:

Query:

				
					SELECT AVG(salary) AS ITAverageSalary
FROM employees
WHERE department = 'IT';

				
			

Output:

IT Average Salary
7000

The query calculates the average salary of employees in the IT department, which is 7,000.

Using AVG() with GROUP BY

The GROUP BY clause is often used with the AVG() function to calculate the average for groups of data. This allows you to calculate averages for distinct categories or groups, such as departments or regions.

Example 3: Average Salary by Department

To calculate the average salary for each department:

Query:

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

				
			

Output:

DepartmentAverage Salary
HR5000
IT7000
Sales6250

The query groups employees by department and calculates the average salary for each department.

Using AVG() with DISTINCT

The DISTINCT keyword can be used with the AVG() function to calculate the average of unique values. This ensures that duplicate values are ignored in the calculation.

Example 4: Average of Unique Salaries

To calculate the average of unique salary values in the employees table:

Query:

				
					SELECT AVG(DISTINCT salary) AS AverageUniqueSalary
FROM employees;

				
			

Output:

Average Unique Salary
6375

The query calculates the average of distinct salary values, ignoring duplicates.

Handling NULL Values with AVG()

The AVG() function automatically ignores NULL values when calculating the average. This means that any NULL values in the column will not affect the result.

Example 5: Calculating Average with NULL Values

Consider a modified employees table where some salaries are NULL:

idnamedepartmentsalary
1John DoeHR5000
2Jane SmithIT6000
3David GreenSalesNULL
4Sarah BrownIT8000
5James WhiteSales5500

To calculate the average salary, ignoring NULL values:

Query:

				
					SELECT AVG(salary) AS AverageSalary
FROM employees;

				
			

Output:

Average Salary
6125

The NULL value is ignored, and the average is calculated from the non-null salaries.

Using AVG() with Joins

You can also use AVG() in queries that involve multiple tables. By joining tables, you can calculate averages that depend on data from multiple sources.

Example 6: Average Order Amount for Each Customer

Consider two tables: customers and orders.

Customer IDCustomer Name
1John Doe
2Jane Smith
Order IDCustomer IDOrder Amount
1011100
1021150
1032200

To calculate the average order amount for each customer:

Query:

				
					SELECT customers.customer_name, AVG(orders.order_amount) AS AverageOrderAmount
FROM customers
JOIN orders ON customers.customer_id = orders.customer_id
GROUP BY customers.customer_name;

				
			

Output:

Customer NameAverage Order Amount
John Doe125
Jane Smith200

The query joins the customers and orders tables, groups by customer name, and calculates the average order amount for each customer.

Using Subqueries with AVG()

Subqueries allow you to combine the AVG() function with other complex queries. For example, you can calculate averages based on dynamically generated results.

Example 7: Finding Employees Earning Above the Average Salary

To find employees whose salaries are higher than the average salary:

Query:

				
					SELECT name, salary
FROM employees
WHERE salary > (SELECT AVG(salary) FROM employees);

				
			

Output:

NameSalary
Sarah Brown8000

The subquery calculates the average salary, and the outer query selects employees who earn more than the average.

Using AVG() Across Multiple Columns

Although the AVG() function is typically used for a single column, you can calculate the average of values from multiple columns by combining them in an expression.

Example 8: Calculating Average Compensation (Salary + Bonus)

Suppose the employees table has an additional bonus column:

IDNameDepartmentSalaryBonus
1John DoeHR5000500
2Jane SmithIT6000600
3David GreenSales7000700

To calculate the average total compensation (salary + bonus):

Query:

				
					SELECT AVG(salary + bonus) AS AverageCompensation
FROM employees;


				
			

Output:

Average Compensation
6350

The query calculates the average total compensation by summing the salary and bonus for each employee and then calculating the average.

Performance Considerations with AVG()

When working with large datasets, performance can become a concern. Here are a few tips to optimize queries involving AVG():

  • Indexing: Ensure that the column being averaged is indexed to speed up query execution.
  • Avoid Unnecessary Grouping: Only use GROUP BY when necessary, as it can add overhead.
  • Use Partitions: If dealing with large tables, partitioning the table can make aggregation functions like AVG() more efficient.

The AVG() function in SQL is a powerful tool for calculating averages in a database. From simple averages of a column to more complex calculations involving conditions, grouping, and joins, the AVG() function allows you to analyze your data effectively. In this chapter, we covered everything you need to know about AVG(), including handling NULL values, using GROUP BY, combining it with DISTINCT, and even calculating averages across multiple columns. With this knowledge, you can confidently use the AVG() function to derive meaningful insights from your data. Happy coding !❤️

Table of Contents

Contact here

Copyright © 2025 Diginode

Made with ❤️ in India