SUM adds the values of a column. AVG gives their average (the sum divided by the number of values).
sql
SELECT SUM(stock), AVG(price) FROM products;text
sum | avg
-----+---------------------
810 | 21.1616666666666667One SELECT can hold several aggregate functions. The result is still one row.
Round the average
An average often has many decimal places. Use ROUND (Chapter 3) around it:
sql
SELECT ROUND(AVG(price), 2) AS avg_price FROM products;An expression inside
The value inside the parentheses can be an expression. It runs for each row first:
sql
SELECT SUM(quantity * unit_price) AS revenue FROM order_items;NULL is skipped
Like COUNT(col), SUM and AVG skip NULL. They do not count it as 0.
ratings
| product_id | stars |
|---|---|
| 1 | 5 |
| 2 | NULL |
| 3 | 3 |
To count a NULL as 0, replace it first: AVG(COALESCE(stars, 0)) returns (5 + 0 + 3) / 3, about 2.67.