This Oracle tutorial explains how to use the Oracle/PLSQL AVG function.
The Oracle/PLSQL AVG function calculates the average value of an expression.
Avg
function operates on a group of rows and return one row of output.
Null values are ignored by avg.
You can use the DISTINCT
keyword to exclude duplicate entries.
The syntax for the Oracle/PLSQL AVG function is:
SELECT AVG( expression ) FROM tables WHERE conditions;
expression can be a numeric field or formula.
The following sql statement calculate average for salary column in employee table.
SELECT AVG(salary) AS "Avg Salary"
FROM employees
WHERE salary > 25000;
We aliased the AVG(salary) expression as "Avg Salary".
The following code shows how to calcualte average for salary column for employee table.
-- w w w .jav a 2 s.c o m
SQL> CREATE TABLE EMP (EMPNO NUMBER(4) NOT NULL,
2 ENAME VARCHAR2(10),
3 JOB VARCHAR2(9),
4 SAL NUMBER(7, 2),
5 DEPTNO NUMBER(2));
SQL> INSERT INTO EMP VALUES (1, 'SMITH', 'CLERK', 800, 20);
SQL> INSERT INTO EMP VALUES (2, 'ALLEN', 'SALESMAN', 1250, 30);
SQL> INSERT INTO EMP VALUES (3, 'WARD', 'SALESMAN', 1250, 30);
SQL> INSERT INTO EMP VALUES (4, 'JONES', 'MANAGER', 2975, 20);
SQL> INSERT INTO EMP VALUES (5, 'MARTIN','SALESMAN', 1250, 30);
SQL> INSERT INTO EMP VALUES (6, 'BLAKE', 'MANAGER', 2850, 30);
SQL> INSERT INTO EMP VALUES (7, 'CLARK', 'MANAGER', 2850, 10);
SQL> INSERT INTO EMP VALUES (8, 'SCOTT', 'ANALYST', 3000, 20);
SQL> INSERT INTO EMP VALUES (9, 'KING', 'PRESIDENT',3000, 10);
SQL> INSERT INTO EMP VALUES (10,'TURNER','SALESMAN', 1500, 30);
SQL> INSERT INTO EMP VALUES (11,'ADAMS', 'CLERK', 1500, 20);
SQL> select avg(sal) from emp;
AVG(SAL)
----------
2020.45455
SQL>
Using AVG
function with group by
clause:
SQL> select job, avg(sal) from emp group by job;
-- w w w . j a v a 2 s . c o m
JOB AVG(SAL)
--------- ----------
CLERK 1150
SALESMAN 1312.5
PRESIDENT 3000
MANAGER 2891.66667
ANALYST 3000
SQL>
Doing the calculation inside avg
fuction:
SQL> select job, avg(sal+ 1000) from emp group by job;
-- from w w w. j a v a 2 s .c om
JOB AVG(SAL+1000)
--------- -------------
CLERK 2150
SALESMAN 2312.5
PRESIDENT 4000
MANAGER 3891.66667
ANALYST 4000
SQL>
Get the distinct average:
SQL>-- from w w w.j a v a 2 s. com
SQL> select job, avg(distinct sal) from emp group by job;
JOB AVG(DISTINCTSAL)
--------- ----------------
ANALYST 3000
CLERK 1150
MANAGER 2912.5
PRESIDENT 3000
SALESMAN 1375
SQL>