SQLite: avg Function
This SQLite tutorial explains how to use the SQLite avg function with syntax and examples.
Description
The SQLite avg function returns the average value of an expression.
Syntax
The syntax for the avg function in SQLite 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
- The 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.
Applies To
The avg function can be used in the following versions of SQLite:
- SQLite 3.8.6, SQLite 3.8.x, SQLite 3.7.x, SQLite 3.6.x
Example - With Single Expression
Let's look at some SQLite avg function examples and explore how to use the avg function in SQLite.
For example, you might wish to know how the average salary of all employees whose last_name is 'Anderson'.
SELECT avg(salary) AS "Avg Salary" FROM employees WHERE last_name = 'Anderson';
In this avg function example, we've aliased the avg(salary) expression as "Avg Salary".
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 $30,000 / year.
SELECT avg(DISTINCT salary) AS "Avg Salary" FROM employees WHERE salary > 30000;
If there were two salaries of $40,000/year, only one of these values would be used in the avg function calculation.
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 monthly salary of all employees.
SELECT avg(salary / 12) AS "Average Monthly Salary" FROM employees;
Example - Using GROUP BY
You could also use the avg function to return the name of the department and the average salary (in the associated department). For example,
SELECT department, SUM(salary) AS "Avg Salary by Dept" FROM employees 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.
Advertisements