What is the SQL Average?
AVG() is one of the five aggregate functions. It allows you to find out the average of a set of selected numerical values.
To find out an average in SQL, you need to select a set of values the average will represent. Therefore, you need to start with the SELECT statement:
SELECT AVG(col_name) FROM tbl_name
The parameters you need to define are simple:
col_nameis the name of the column
tbl_nameis the name of the table
Using SQL Average Function: An Example
To get a better idea on what is an average in SQL and how you can work with it, we will see a simple example using a demo database and a few code examples for you to try out.
Theory is great, but we recommend digging deeper!
A Demo Database
In the example below, you can see a table called
|3||Cheese||3||4||5 kg boxes||11||11||6|
|4||Milk||3||3||5 L bottles||22||56||12|
Counting the Average
Using the statement below, you can calculate the average price of those listed in the table:
SELECT AVG(Price) AS PriceAverageID FROM Products;
Working With the Average
Now, in the code example below, you can see how to only pick out the values that are higher than the average in SQL. We also choose two columns to be displayed –
SELECT Name, Price FROM Products WHERE Price>(SELECT AVG(Price) FROM Products);