SQL AGGREGATE FUNCTIONS – AVG
SELECT AVG(column1) FROM table_name WHERE condition;
Usually, the aggregate functions are used in conjunction with the GROUP BY/ HAVING clause, which gives even more meaningful results. The syntax for the query using AVG function using GROUP BY / HAVING clause is mentioned below –
SELECT column1, AVG(column2) FROM table_name WHERE condition1 GROUP BY column1 HAVING condition2;
At first, these might look little complicated, but once we go over few examples, it will make more sense.
Illustration – Consider the below employee table in the database which stores the information pertaining to employees in ABC company –
Query 1 – What is the average salary of all the employees of ABC company?
SELECT AVG(salary) FROM employee;
Query 2 – What is the average salary of all employees of ABC company who belongs to sales department?
SELECT AVG(salary) FROM employee WHERE department=’sales’;
Query 3 – What is the average salary of employees in ABC company by each department.
SELECT Department, AVG(salary) FROM employee GROUP BY Department;
Query 4 – What is the list of departments at ABC company, which has more than average employee salary less than or equal to 90000 in their department?
SELECT Department, AVG(salary) FROM employee GROUP BY Department HAVING AVG(salary) <= 90000;