Averaging values with AVG #
AVG is an aggregate function that computes the mean of a numeric column across all the rows.
SELECT
AVG(column_name) AS average
FROM
table_name;
AVG(column_name) adds up every value in column_name and divides by the number of rows. Like SUM, rows where the column is NULL are skipped rather than counted as zero.
Example #
SELECT
AVG(age) AS average_age
FROM
customers;
Result:
+--------------+
| average_age |
+--------------+
| 71.6 |
+--------------+
This tells us the mean age across all rows in customers.
Exercise #
Write a command that computes the average price across every row in the products table.
- The result has an
average_pricecolumn. - The value of
average_pricematches the average of thepricecolumn inproducts.
Solution
SELECT
AVG(price) AS average_price
FROM
products;
Basic Data Retrieval
Filtering Data
Aggregating Data
Joining Tables
Creating and Managing Tables
Transactions and Data Integrity