totn Oracle Functions

Oracle / PLSQL: AVG Function

This Oracle tutorial explains how to use the Oracle/PLSQL AVG function with syntax and examples.

Description

The Oracle/PLSQL AVG function returns the average value of an expression.

Syntax

The syntax for the AVG function in Oracle/PLSQL is:

SELECT AVG(aggregate_expression)
FROM tables
[WHERE conditions];

OR the syntax for the AVG function when grouping the results by one or more columns is:

SELECT expression1, expression2, ... expression_n,
       AVG(aggregate_expression)
FROM tables
[WHERE conditions]
GROUP BY expression1, expression2, ... expression_n;

Parameters or Arguments

expression1, expression2, ... expression_n
Expressions that are not encapsulated within the AVG function and must be included in the GROUP BY clause at the end of the SQL statement.
aggregate_expression
This is the column or expression that will be averaged.
tables
The tables that you wish to retrieve records from. There must be at least one table listed in the FROM clause.
WHERE conditions
Optional. These are conditions that must be met for the records to be selected.

Returns

The AVG function returns a numeric value.

Applies To

The AVG function can be used in the following versions of Oracle/PLSQL:

  • Oracle 12c, Oracle 11g, Oracle 10g, Oracle 9i, Oracle 8i

Example - With Single Field

Let's look at some Oracle AVG function examples and explore how to use the AVG function in Oracle/PLSQL.

For example, you might wish to know how the average salary of all employees whose salary is above $25,000 / year.

SELECT AVG(salary) AS "Avg Salary"
FROM employees
WHERE salary > 25000;

In this AVG function example, we've aliased the AVG(salary) expression as "Avg Salary". As a result, "Avg Salary" will display as the field name when the result set is returned.

Example - Using DISTINCT

You can use the DISTINCT clause within the AVG function. For example, the SQL statement below returns the average salary of unique salary values where the salary is above $25,000 / year.

SELECT AVG(DISTINCT salary) AS "Avg Salary"
FROM employees
WHERE salary > 25000;

If there were two salaries of $30,000/year, only one of these values would be used in the AVG function.

Example - Using Formula

The expression contained within the AVG function does not need to be a single field. You could also use a formula. For example, you might want the average commission.

SELECT AVG(sales * 0.10) AS "Average Commission"
FROM orders;

Example - Using GROUP BY

You could also use the AVG function to return the name of the department and the average sales (in the associated department). For example,

SELECT department, AVG(sales) AS "Avg sales"
FROM order_details
GROUP BY department;

Because you have listed one column in your SELECT statement that is not encapsulated in the AVG function, you must use a GROUP BY clause. The department field must, therefore, be listed in the GROUP BY section.