MySQL: Average Function

Profile picture for user arilio666

The average function avg() in MySQL returns the average value of the column name we provide within the bracket of avg().




For example purpose we will be using the order_details table:

Here is the query we need to do:

Write a query to retrieve the total amount received from all orders, the average amount, and round answers to the nearest integer.

select (price_each * quantity_ordered) as totalAmount, avg(price_each * quantity_ordered) as avgAmount, round(price_each * quantity_ordered) as totalAmount_round, round(avg(price_each * quantity_ordered)) as avgAmount_round from order_details;

  1. So as we can see from the query, we have multiplied price_each and quantity_ordered to get the total amount.
  2. We also got the average for the same using avg() function, and within that, we used the expression to get the total amount.
  3. This will yield an average, and we aliased it to avgAmount.
  4. As per requirement, we rounded off both the total amount and average total amount answers to the nearest integer from the order_details table.