Lesson 9 | SQL `AVG` function |

Objective | Understand the use of the `AVG` function. |

If you have used worksheets and spreadsheets, you have probably used the

`AVG`

function,
which allows you to average the values in a given column. This works exactly the same in SQL, where the `AVG`

function lets you average the numeric values contained within a given column. The syntax is identical to the `SUM`

function. You simply call it and enclose in parentheses the name of the column you want to average:
SELECT MyName, MyAddress, MyNumber, AVG(MyNumber) FROM MyTable

This returns the different columns requested, plus one additional column, unnamed, that contains the average value for the MyNumber values.

Use the aggregate function AVG() to find the average, or arithmetic mean, of a set of values. The arithmetic mean is the sum of a set of quantities divided by the number of quantities in the set. To calculate the average of a set of values:

Type:

The results data type is at least as precise as the most precise data type used in expr.

Type:

AVG(expr)expr is a column name, literal, or numeric expression.

The results data type is at least as precise as the most precise data type used in expr.

Listing 4.9 Some AVG() queries. See Figure 4.9 for the results.

SELECT AVG(price * 2) AS "AVG(price * 2)" FROM titles; SELECT AVG(sales) AS "AVG(sales)", SUM(sales) AS "SUM(sales)" FROM titles WHERE type = 'business'; SELECT title_id, sales FROM titles WHERE sales > (SELECT AVG(sales) FROM titles) ORDER BY sales DESC;

AVG(price * 2) -------------- 36.775000 AVG(sales) SUM(sales) ---------- ---------- NULL NULL title_id sales -------- ------- T07 1500200 T05 201440