How do you use the AVG function to calculate the average value of a numeric column?
Posted by NickCrt
Last Updated: July 22, 2024
The AVG function in SQL is used to calculate the average value of a numeric column in a database table. Here's how you can use the AVG function:
Basic Syntax
SELECT AVG(column_name) AS average_value
FROM table_name;
Explanation:
- SELECT: This keyword is used to specify the columns that you want to retrieve. - AVG(column_name): This is the function that calculates the average. Replace column_name with the name of the numeric column for which you want to calculate the average. - AS average_value: This gives a name (alias) to the calculated average result for easier reference. You can choose any name you prefer. - FROM table_name: Replace table_name with the name of the table from which you want to retrieve the data.
Example
Suppose you have a table called Sales with a column amount that contains numeric values representing sales amounts. To calculate the average sales amount, you would write:
SELECT AVG(amount) AS average_sales
FROM Sales;
Grouping Data
You can also use the AVG function in combination with the GROUP BY clause to calculate averages for different groups. For example, if you want to calculate the average sales amount by each salesperson, you would use:
SELECT salesperson_id, AVG(amount) AS average_sales
FROM Sales
GROUP BY salesperson_id;
Handling NULL Values
The AVG function automatically ignores NULL values in the specified column when calculating the average.
Conclusion
That's how you can use the AVG function to calculate the average value of a numeric column in SQL. Just remember to substitute column_name and table_name with your actual database column and table names.
Related Content