Function or operator · Grouping and calculating

AVG

AVG computes the average of the non-NULL values. It does not count missing values as zero.

AVG example

First we exclude out-of-stock products. We add COUNT(*) so the denominator is visible and the result can be interpreted.

SQL
SELECT COUNT(*) AS products_with_stock,
       ROUND(AVG(price), 2) AS average_price
FROM products
WHERE stock > 0;

The average is computed over seven products. It is not weighted by stock: a product with thirty units counts the same as one with two.

How AVG is used

Round for display, not for filtering. Keep full precision during the calculation and apply ROUND to the displayed result. Rounding each row before averaging can change the final value.

What changes from case to case

AVG and NULL values

If a column has ten rows and two of them are NULL, AVG(column_name) divides by eight. Turning those nulls into zero with COALESCE changes the question and can change the average; only do it when zero really is the missing value.

Simple and weighted averages on the same data

You sell one notebook at 10 pounds and nine pencils at 2 pounds each. The average price of the two products is 6 pounds, but the average price across the ten units sold is 2.80 pounds. This self-contained example runs in SQLite without loading the course tables.

SQL · SQLite
WITH sales_average (product, price, quantity) AS (
  VALUES ('Notebook', 10.0, 1), ('Pencil', 2.0, 9)
)
SELECT AVG(price) AS average_products,
       SUM(price * quantity) / NULLIF(SUM(quantity), 0) AS average_units
FROM sales_average;
The question decides the denominator
average_productsaverage_units
6,02,8

AVG(price) gives every product the same weight. The second expression divides the 28 pounds of sales by 10 units. NULLIF avoids dividing by zero: if there are no units, the weighted average is undefined and returns NULL. The prices in the example are decimals so the fractional part is kept.

Also check what a missing value means

SQL · SQLite
WITH measures (value) AS (
  VALUES (10.0), (20.0), (NULL)
)
SELECT COUNT(*) AS rows,
       COUNT(value) AS known_values,
       AVG(value) AS average_known,
       AVG(COALESCE(value, 0)) AS average_with_zero
FROM measures;

The result is 3, 2, 15.0, 10.0. The third row has no known measurement. Replacing it with zero brings it into the calculation and changes the denominator. Use COALESCE only if the missing value really means zero; do not add it to hide the fact that information is missing.