SQL AVG() Function |
SQL Sample Code - SQL AVG() Function |
| SELECT AVG(column_name) FROM table_name; |
See the examples section below for an explanation of the Average function.
| What does the AVG( ) Function do? |
The SQL AVG() function calculates the ‘mean’ average of all values in a column.
Note: The AVG() function can only be used on database columns with numeric based data-types. See our data-types sections for more information.
Sample 1 – SQL AVG() Function |
In this SQL sample we will use the database table ‘tblCompany’.
| Company_ID | CompanyName | Address | Town | Sales |
| 1 | SQL Sample | 1 Sample St | Hamburg | 10000 |
| 2 | SQL Code Land | 2 Code Rd | Hamburg | 20000 |
| 3 | Sample Code World | 66 SQL St | Curry | 18000 |
| 4 | SQL Reference Ltd | 34 Reference St | Pisa | 17000 |
In this SQL sampl we want to know the average AVG() for the Sales column in the tblCompany table.
Use the SELECT statement below:
| SELECT AVG(Sales) AS Average_Sales FROM tblCompany; |
The result will look like this:
| Average_Sales |
| 16250 |
Note: the AS operator is used to name the result column as ‘Avreage_Sales’. See the Alias section of this website to learn more about renaming database columns and tables.
Sample 2 – SQL AVG() Function using GROUP BY. |
In this SQL sample we will use the database table ‘tblCompany’.
| Company_ID | CompanyName | Address | Town | Sales |
| 1 | SQL Sample | 1 Sample St | Hamburg | 10000 |
| 2 | SQL Code Land | 2 Code Rd | Hamburg | 20000 |
| 3 | Sample Code World | 66 SQL St | Curry | 18000 |
| 4 | SQL Reference Ltd | 34 Reference St | Pisa | 17000 |
In this SQL sample we want to know the average AVG() for the Sales column in the tblCompany database table for each Town.
Use the SELECT statement below:
| SELECT Town, AVG(Sales) FROM tblCompany GROUP BY Town; |
The result for the average - AVG will look like this:
| Town | AVG(Sales) |
| Hamburg | 15000 |
| Curry | 18000 |
| Pisa | 17000 |
Related SQL Sample Code:
|
|